From b75684b25489f934ae7a108aa21b2653e96222ac Mon Sep 17 00:00:00 2001
From: sophelper <123211521@163.com>
Date: Tue, 3 Nov 2026 01:09:24 +0800
Subject: [PATCH] =?UTF-8?q?feat(Engine):=20SOP=20=E5=BC=95=E6=93=8E=20?=
=?UTF-8?q?=E2=80=94=20=E9=85=8D=E6=96=B9=20YAML=20=E5=8A=A0=E8=BD=BD/?=
=?UTF-8?q?=E6=A0=A1=E9=AA=8C=20+=20=E6=9D=A1=E4=BB=B6=E5=88=A4=E5=AE=9A?=
=?UTF-8?q?=20+=20=E8=BF=9D=E8=A7=84=20+=20=E7=8A=B6=E6=80=81=E6=9C=BA?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 配方 schema 沿用参考项目(sop/settings/regions/steps),现有 YAML 可直接搬
- 只实现其配方里真被用过的 8 个方法,未实现的在加载期就报出来
- 稳定帧门控按 (步骤Id,条件序号) 计数,time_elapsed/hand_move/hand_action 豁免
- 违规:超时/跳步(仅看紧邻下一步)/必留物被拿走,同类 3s 冷却
- 引擎层只用自有 DetRect,不引用任何 WPF 类型,事件解耦给 UI
- configs/sop/demo.yaml: 不依赖检测模型的最小闭环示例
---
configs/sop/demo.yaml | 108 ++++++
.../Sop/ConditionEvaluator.cs | 328 ++++++++++++++++++
src/SopHelper.Engine/Sop/SopConfig.cs | 248 +++++++++++++
src/SopHelper.Engine/Sop/SopConfigLoader.cs | 129 +++++++
src/SopHelper.Engine/Sop/SopEngine.cs | 267 ++++++++++++++
src/SopHelper.Engine/Sop/ViolationDetector.cs | 199 +++++++++++
6 files changed, 1279 insertions(+)
create mode 100644 configs/sop/demo.yaml
create mode 100644 src/SopHelper.Engine/Sop/ConditionEvaluator.cs
create mode 100644 src/SopHelper.Engine/Sop/SopConfig.cs
create mode 100644 src/SopHelper.Engine/Sop/SopConfigLoader.cs
create mode 100644 src/SopHelper.Engine/Sop/SopEngine.cs
create mode 100644 src/SopHelper.Engine/Sop/ViolationDetector.cs
diff --git a/configs/sop/demo.yaml b/configs/sop/demo.yaml
new file mode 100644
index 0000000..bb19d3e
--- /dev/null
+++ b/configs/sop/demo.yaml
@@ -0,0 +1,108 @@
+# SopHelper 示例配方 —— 区域坐标必须按现场画面重新标定,别照抄
+#
+# 这份配方只用引擎确实实现的方法(见 SopHelper.Engine/Sop/ConditionMethod.cs):
+# time_elapsed / hand_in_region / hand_move / object_in_zone / object_present
+# 区域坐标是绝对像素(相机原始分辨率下的坐标),先接相机、截图、再标定。
+
+sop:
+ name: 示例-取放流程
+ version: "1.0"
+ description: 演示最小闭环:手部就位 → 计时 → 取放搬运(不依赖检测模型)
+
+ settings:
+ confidence_threshold: 0.6
+ stable_frames: 3
+ position_tolerance: 30
+ enable_timeout_detection: true
+ enable_skip_detection: true
+ auto_reset_on_complete: true
+ reset_delay_sec: 2
+ frame_stride: 2
+
+ # 只用手部 + 计时时可以不写 model;要用 object_* 类条件就必须写
+ # model:
+ # path: models/yolov8n.onnx
+ # input_size: 640
+ # classes:
+ # - cup
+ # - screw
+
+ regions:
+ table:
+ x1: 200
+ y1: 420
+ x2: 760
+ y2: 820
+ name: 桌面操作区
+ color: "#4CAF50"
+ tray:
+ x1: 60
+ y1: 120
+ x2: 400
+ y2: 380
+ name: 来料区
+ color: "#2196F3"
+ out:
+ x1: 900
+ y1: 150
+ x2: 1240
+ y2: 420
+ name: 成品区
+ color: "#FF9800"
+
+ steps:
+ - id: 1
+ name: 手放到桌面上方
+ description: 手进入桌面操作区即算就位
+ timeout: 30
+ standard_duration_ms: 3000
+ detection:
+ method: hand_in_region
+ region: table
+ hand: any
+ stable_frames: 3
+ violation_rules:
+ - type: timeout
+ description: 手迟迟没有放到操作位
+ severity: 1
+
+ - id: 2
+ name: 保持 2 秒
+ description: 纯计时,用来演示计时类条件
+ timeout: 0
+ detection:
+ method: time_elapsed
+ duration_ms: 2000
+
+ - id: 3
+ name: 从操作区拿到料区
+ description: 手从桌面操作区移到料区(轨迹证据来自上一帧)
+ timeout: 30
+ detection:
+ method: hand_move
+ from_region: table
+ to_region: tray
+ hand: any
+ tolerance: 30
+ violation_rules:
+ - type: timeout
+ description: 取料超时
+ severity: 1
+
+ - id: 4
+ name: 放入成品区
+ description: 手从料区移到成品区
+ timeout: 30
+ detection:
+ method: hand_move
+ from_region: tray
+ to_region: out
+ hand: any
+ tolerance: 30
+ violation_rules:
+ - type: timeout
+ description: 放入超时
+ severity: 1
+ - type: wrong_order
+ description: 没有按顺序放入
+ severity: 2
diff --git a/src/SopHelper.Engine/Sop/ConditionEvaluator.cs b/src/SopHelper.Engine/Sop/ConditionEvaluator.cs
new file mode 100644
index 0000000..7fe31c7
--- /dev/null
+++ b/src/SopHelper.Engine/Sop/ConditionEvaluator.cs
@@ -0,0 +1,328 @@
+using SopHelper.Engine.Common;
+
+namespace SopHelper.Engine.Sop;
+
+///
+/// 条件判定结果
+///
+public class ConditionResult
+{
+ /// 是否满足
+ public bool IsMet { get; set; }
+
+ /// 说明(不满足时给出原因,界面直接显示)
+ public string Message { get; set; } = "";
+}
+
+///
+/// 单条件判定 + 稳定帧门控。
+/// 门控语义照搬参考项目(它自己踩过坑):按 (步骤Id, 条件序号) 累计连续命中帧数,
+/// 达标才放行;未命中即清零;Start/Reset 必须清空,否则新一轮会"秒过"绕过防抖。
+///
+public class ConditionEvaluator
+{
+ private readonly SopSettings _settings;
+ private readonly Dictionary _regions;
+
+ /// 稳定帧计数:key = "步骤Id:条件序号"
+ private readonly Dictionary _stablePassCounts = [];
+
+ /// 每只手最近访问过的区域(hand_move 的 from 证据)
+ private readonly Dictionary> _handVisitedRegions = [];
+
+ /// 每个物体最近访问过的区域(手搬运物体时,from 证据来自物体轨迹)
+ private readonly Dictionary> _objectVisitedRegions = new(StringComparer.OrdinalIgnoreCase);
+
+ /// 步骤进入时刻(time_elapsed 用)
+ private readonly Dictionary _stepEnterTime = [];
+
+ ///
+ /// 单条件判定 + 稳定帧门控
+ ///
+ public ConditionEvaluator(SopSettings settings, Dictionary regions)
+ {
+ _settings = settings;
+ _regions = regions;
+ }
+
+ ///
+ /// 步骤进入时登记时刻(引擎在推进步骤时调用)
+ ///
+ public void NoteStepEntered(int stepId, DateTime now)
+ {
+ _stepEnterTime.TryAdd(stepId, now);
+ }
+
+ ///
+ /// 清空跨帧状态(工作流 Start/Reset 时调用)
+ ///
+ public void Reset()
+ {
+ _stablePassCounts.Clear();
+ _handVisitedRegions.Clear();
+ _objectVisitedRegions.Clear();
+ _stepEnterTime.Clear();
+ }
+
+ ///
+ /// 判定一个步骤的全部条件(AND 短路:一个步骤 = 一个检测节点,多个条件全满足才过)
+ ///
+ public ConditionResult EvaluateStep(StepDef step, FrameResult frame, int probeSeed = 0)
+ {
+ var condition = step.Detection;
+ if (condition is null)
+ return new ConditionResult { IsMet = false, Message = "无判定条件" };
+
+ var raw = EvaluateCondition(step, condition, frame);
+
+ // 轨迹登记(供下一帧的 from 判定用)——先判后登记,本帧命中不算"之前访问过"
+ var result = ApplyStableGate(step.Id, probeSeed, condition, raw);
+
+ TrackVisits(step, condition, frame);
+
+ return result;
+ }
+
+ ///
+ /// 单条方法的判定(不含门控)
+ ///
+ private ConditionResult EvaluateCondition(StepDef step, StepCondition condition, FrameResult frame)
+ {
+ var conf = condition.MinConfidence > 0 ? condition.MinConfidence : _settings.ConfidenceThreshold;
+ var tolerance = condition.Tolerance > 0 ? condition.Tolerance : _settings.PositionTolerance;
+
+ switch (condition.Method.ToLowerInvariant())
+ {
+ case ConditionMethod.TimeElapsed:
+ {
+ if (!_stepEnterTime.TryGetValue(step.Id, out var entered))
+ return new ConditionResult { IsMet = false, Message = "计时未开始" };
+
+ var elapsed = (DateTime.Now - entered).TotalMilliseconds;
+ var need = condition.DurationMs > 0 ? condition.DurationMs : 1000;
+
+ return elapsed >= need
+ ? new ConditionResult { IsMet = true, Message = $"已持续 {elapsed / 1000:F1}s / 需 {need / 1000:F1}s" }
+ : new ConditionResult { IsMet = false, Message = $"持续 {elapsed / 1000:F1}s,还差 {(need - elapsed) / 1000:F1}s" };
+ }
+
+ case ConditionMethod.ObjectPresent:
+ {
+ var hit = FindDetection(frame, condition.TargetObject, conf);
+ return hit is null
+ ? No($"未检出 {condition.TargetObject}")
+ : Yes($"检出 {condition.TargetObject} {hit.Confidence:F2}");
+ }
+
+ case ConditionMethod.ObjectInZone:
+ {
+ var region = Region(condition.Region);
+ if (region is null) return No($"区域 {condition.Region} 不存在");
+
+ var hit = FindDetection(frame, condition.TargetObject, conf);
+
+ if (hit is null) return No($"未检出 {condition.TargetObject}");
+
+ var (cx, cy) = hit.Rect.Center;
+
+ return region.Value.Contains(cx, cy, tolerance)
+ ? Yes($"{condition.TargetObject} 已进入 {condition.Region}")
+ : No($"{condition.TargetObject} 未在 {condition.Region} 内");
+ }
+
+ case ConditionMethod.PersonPresent:
+ {
+ var target = string.IsNullOrWhiteSpace(condition.TargetObject) ? "person" : condition.TargetObject;
+ var hit = FindDetection(frame, target, conf);
+
+ return hit is null ? No($"未检出 {target}") : Yes($"{target} 在场 {hit.Confidence:F2}");
+ }
+
+ case ConditionMethod.HandInRegion:
+ {
+ var region = Region(condition.Region);
+ if (region is null) return No($"区域 {condition.Region} 不存在");
+
+ var hand = PickHand(frame, condition.Hand);
+ if (hand is null) return No("未检出手");
+
+ var (hx, hy) = hand.Center;
+
+ return region.Value.Contains(hx, hy, tolerance)
+ ? Yes($"手已进入 {condition.Region}")
+ : No($"手未在 {condition.Region} 内");
+ }
+
+ case ConditionMethod.HandNearObject:
+ {
+ var hand = PickHand(frame, condition.Hand);
+ if (hand is null) return No("未检出手");
+
+ var hit = FindDetection(frame, condition.TargetObject, conf);
+ if (hit is null) return No($"未检出 {condition.TargetObject}");
+
+ var handRect = new DetRect(hand.Center.Item1 - 1, hand.Center.Item2 - 1, 2, 2);
+
+ return handRect.Intersects(hit.Rect, tolerance)
+ ? Yes($"手已靠近 {condition.TargetObject}")
+ : No($"手尚未靠近 {condition.TargetObject}");
+ }
+
+ case ConditionMethod.HandMove:
+ case ConditionMethod.HandAction:
+ {
+ var from = Region(condition.FromRegion);
+ var to = Region(condition.ToRegion);
+
+ if (from is null) return No($"起点区域 {condition.FromRegion} 不存在");
+ if (to is null) return No($"终点区域 {condition.ToRegion} 不存在");
+
+ var hand = PickHand(frame, condition.Hand);
+ if (hand is null) return No("未检出手");
+
+ // 终点:手(或手+物)当前在 to 区
+ var (hx, hy) = hand.Center;
+ if (!to.Value.Contains(hx, hy, tolerance))
+ return No($"手未到 {condition.ToRegion}");
+
+ // 起点证据:本帧之前访问过 from 区。
+ // 搬运场景优先看物体轨迹——喝水这类配方判的是"杯子到达嘴边",
+ // from 证据应来自物体,否则放回步骤会卡在 visitedFrom=false。
+ var visited = VisitedFrom(condition, hand);
+
+ return visited
+ ? Yes($"已从 {condition.FromRegion} 移动到 {condition.ToRegion}")
+ : No($"未记录到从 {condition.FromRegion} 出发的轨迹");
+ }
+
+ default:
+ return No($"方法 '{condition.Method}' 未实现");
+ }
+ }
+
+ ///
+ /// 稳定帧门控。time_elapsed / hand_move / hand_action 豁免
+ /// (自带时序或瞬时交互语义,与参考项目的豁免清单一致)。
+ ///
+ private ConditionResult ApplyStableGate(int stepId, int probeSeed, StepCondition condition, ConditionResult raw)
+ {
+ var method = condition.Method.ToLowerInvariant();
+
+ var exempt = method == ConditionMethod.TimeElapsed
+ || method == ConditionMethod.HandMove
+ || method == ConditionMethod.HandAction;
+
+ if (exempt) return raw;
+
+ var required = condition.StableFrames > 0 ? condition.StableFrames : _settings.StableFrames;
+ if (required <= 1) return raw;
+
+ var key = $"{stepId}:{probeSeed}";
+
+ if (raw.IsMet)
+ {
+ _stablePassCounts.TryGetValue(key, out var count);
+ count++;
+ _stablePassCounts[key] = count;
+
+ if (count < required)
+ {
+ raw.IsMet = false;
+ raw.Message += $"(稳定帧 {count}/{required})";
+ }
+ }
+ else
+ {
+ _stablePassCounts[key] = 0;
+ }
+
+ return raw;
+ }
+
+ ///
+ /// 记录本帧的轨迹证据(下一帧才用得上)
+ ///
+ private void TrackVisits(StepDef step, StepCondition condition, FrameResult frame)
+ {
+ var tolerance = condition.Tolerance > 0 ? condition.Tolerance : _settings.PositionTolerance;
+
+ // 手访问过哪些区域
+ foreach (var hand in frame.Hands)
+ {
+ var key = hand.HandType.ToString();
+ if (!_handVisitedRegions.TryGetValue(key, out var set))
+ _handVisitedRegions[key] = set = [];
+
+ foreach (var (name, rect) in _regions)
+ {
+ var (hx, hy) = hand.Center;
+ if (rect.Contains(hx, hy, tolerance)) set.Add(name);
+ }
+ }
+
+ // 物体访问过哪些区域
+ foreach (var det in frame.Detections)
+ {
+ if (!_objectVisitedRegions.TryGetValue(det.Label, out var set))
+ _objectVisitedRegions[det.Label] = set = [];
+
+ var (cx, cy) = det.Rect.Center;
+
+ foreach (var (name, rect) in _regions)
+ {
+ if (rect.Contains(cx, cy, tolerance)) set.Add(name);
+ }
+ }
+ }
+
+ ///
+ /// from 区证据:物体轨迹优先(搬运),没有就看手自己的轨迹
+ ///
+ private bool VisitedFrom(StepCondition condition, Hand hand)
+ {
+ if (!string.IsNullOrWhiteSpace(condition.TargetObject)
+ && _objectVisitedRegions.TryGetValue(condition.TargetObject, out var objectVisited)
+ && objectVisited.Contains(condition.FromRegion))
+ {
+ return true;
+ }
+
+ return _handVisitedRegions.TryGetValue(hand.HandType.ToString(), out var handVisited)
+ && handVisited.Contains(condition.FromRegion);
+ }
+
+ ///
+ /// 取判定用的手。hand:any 优先右手(与参考项目一致)
+ ///
+ private static Hand? PickHand(FrameResult frame, string hand)
+ {
+ if (frame.Hands.Count == 0) return null;
+
+ return hand.ToLowerInvariant() switch
+ {
+ "left" or "左手" => frame.Hands.FirstOrDefault(h => h.HandType == HandType.Left),
+ "right" or "右手" => frame.Hands.FirstOrDefault(h => h.HandType == HandType.Right),
+ _ => frame.Hands.FirstOrDefault(h => h.HandType == HandType.Right) ?? frame.Hands[0],
+ };
+ }
+
+ ///
+ /// 按类别找检测框(取置信度最高的那个)
+ ///
+ private static Detection? FindDetection(FrameResult frame, string label, float minConf)
+ {
+ return frame.Detections
+ .Where(d => d.Label.Equals(label, StringComparison.OrdinalIgnoreCase) && d.Confidence >= minConf)
+ .OrderByDescending(d => d.Confidence)
+ .FirstOrDefault();
+ }
+
+ private DetRect? Region(string name)
+ {
+ return _regions.TryGetValue(name, out var rect) ? rect : null;
+ }
+
+ private static ConditionResult Yes(string message) => new() { IsMet = true, Message = message };
+
+ private static ConditionResult No(string message) => new() { IsMet = false, Message = message };
+}
diff --git a/src/SopHelper.Engine/Sop/SopConfig.cs b/src/SopHelper.Engine/Sop/SopConfig.cs
new file mode 100644
index 0000000..d6e53c5
--- /dev/null
+++ b/src/SopHelper.Engine/Sop/SopConfig.cs
@@ -0,0 +1,248 @@
+using YamlDotNet.Serialization;
+
+namespace SopHelper.Engine.Sop;
+
+///
+/// SOP 配方(YAML 反序列化根)。字段名保持与参考项目一致,现有配方文件可直接搬。
+///
+public class SopConfig
+{
+ /// sop 根节点
+ public SopBody Sop { get; set; } = new();
+
+ /// 加载过程中的提醒(缺字段、未知方法等,界面要显示)
+ [YamlIgnore]
+ public List Warnings { get; } = [];
+}
+
+///
+/// sop 节点
+///
+public class SopBody
+{
+ /// 配方名
+ public string Name { get; set; } = "";
+
+ /// 版本
+ public string Version { get; set; } = "1.0";
+
+ /// 说明
+ public string Description { get; set; } = "";
+
+ /// 全局设置
+ public SopSettings Settings { get; set; } = new();
+
+ /// 区域定义(键 = 配方里引用的区域名)
+ public Dictionary Regions { get; set; } = new(StringComparer.OrdinalIgnoreCase);
+
+ /// 步骤列表(按书写顺序执行)
+ public List Steps { get; set; } = [];
+
+ /// 默认模型(缺省=只做手部与计时;写了就跑 YOLO)
+ public ModelDef? Model { get; set; }
+}
+
+///
+/// sop.settings
+///
+public class SopSettings
+{
+ /// 全局置信度阈值
+ public float ConfidenceThreshold { get; set; } = 0.6f;
+
+ /// 默认稳定帧数(条件未写 stable_frames 时用它)
+ public int StableFrames { get; set; } = 5;
+
+ /// 区域命中容差(像素)
+ public float PositionTolerance { get; set; } = 20f;
+
+ /// 启用超时违规
+ public bool EnableTimeoutDetection { get; set; } = true;
+
+ /// 启用跳步/错序违规
+ public bool EnableSkipDetection { get; set; } = true;
+
+ /// 整轮完成后自动复位
+ public bool AutoResetOnComplete { get; set; } = true;
+
+ /// 复位前停留秒数
+ public int ResetDelaySec { get; set; } = 1;
+
+ /// 抽帧间隔(1=每帧都判;推理跟不上时调大可稳住帧率)
+ public int FrameStride { get; set; } = 1;
+}
+
+///
+/// 区域定义(绝对像素坐标,须在真机画面上标定)
+///
+public class RegionDef
+{
+ /// 左上 X
+ public int X1 { get; set; }
+
+ /// 左上 Y
+ public int Y1 { get; set; }
+
+ /// 右下 X
+ public int X2 { get; set; }
+
+ /// 右下 Y
+ public int Y2 { get; set; }
+
+ /// 区域名(显示用)
+ public string Name { get; set; } = "";
+
+ /// 说明
+ public string Description { get; set; } = "";
+
+ /// 显示颜色
+ public string Color { get; set; } = "#4CAF50";
+}
+
+///
+/// 模型定义
+///
+public class ModelDef
+{
+ /// onnx 路径(相对程序目录)
+ public string Path { get; set; } = "";
+
+ /// 类别名,顺序必须与训练时一致
+ public List Classes { get; set; } = [];
+
+ /// 输入尺寸
+ public int InputSize { get; set; } = 640;
+}
+
+///
+/// 步骤定义
+///
+public class StepDef
+{
+ /// 步骤号(不必从 1 开始,状态机取最小值起步)
+ public int Id { get; set; }
+
+ /// 步骤名
+ public string Name { get; set; } = "";
+
+ /// 说明
+ public string Description { get; set; } = "";
+
+ /// 本步超时秒数(0 = 不限制)
+ public int Timeout { get; set; }
+
+ /// 标准节拍毫秒(报表对比用,判定不参与)
+ public int StandardDurationMs { get; set; }
+
+ /// 本步判定条件(AND,全部满足才算完成)
+ public StepCondition? Detection { get; set; }
+
+ /// 本步期间必须常在的物体,被拿走即违规
+ public List MustKeep { get; set; } = [];
+
+ /// 本步完成时必须存在的物体(漏放/缺料)
+ public List RequiredObjects { get; set; } = [];
+
+ /// 违规规则
+ public List ViolationRules { get; set; } = [];
+}
+
+///
+/// 步骤判定条件
+///
+public class StepCondition
+{
+ /// 判定方法(见 ConditionMethod)
+ public string Method { get; set; } = "";
+
+ /// 目标物体类别(物体类条件用)
+ public string TargetObject { get; set; } = "";
+
+ /// 主区域名
+ public string Region { get; set; } = "";
+
+ /// 起点区域名(hand_move 的 from)
+ public string FromRegion { get; set; } = "";
+
+ /// 终点区域名(hand_move 的 to)
+ public string ToRegion { get; set; } = "";
+
+ /// 手:left / right / any
+ public string Hand { get; set; } = "any";
+
+ /// 手-物相邻容差(像素)
+ public float Tolerance { get; set; } = 60f;
+
+ /// 本条件置信度阈值
+ public float MinConfidence { get; set; } = 0.7f;
+
+ /// 稳定帧数(连续命中才放行)
+ public int StableFrames { get; set; } = 5;
+
+ /// 计时毫秒(time_elapsed 用)
+ public int DurationMs { get; set; }
+
+ /// 动作语义(hand_action 用:pickup / putdown)
+ public string Action { get; set; } = "";
+}
+
+///
+/// 配方支持的条件方法。只列参考项目配方里真被用过的(按其统计覆盖其 90% 实际用法),
+/// 没实现的枚举成员一律不写进配方示例。
+///
+public static class ConditionMethod
+{
+ /// 目标出现在画面(1 次)
+ public const string ObjectPresent = "object_present";
+
+ /// 目标在区域内(14 次,第二常用)
+ public const string ObjectInZone = "object_in_zone";
+
+ /// 手在区域内(12 次)
+ public const string HandInRegion = "hand_in_region";
+
+ /// 手从 A 区移到 B 区(7 次;配方里写作 hand_move)
+ public const string HandMove = "hand_move";
+
+ /// 取放动作(10 次;= hand_move + 动作语义)
+ public const string HandAction = "hand_action";
+
+ /// 手-物相邻(3 次)
+ public const string HandNearObject = "hand_near_object";
+
+ /// 人在场(7 次,走 COCO 的 person)
+ public const string PersonPresent = "person_present";
+
+ /// 持续计时(16 次,最常用)
+ public const string TimeElapsed = "time_elapsed";
+}
+
+///
+/// 违规规则
+///
+public class ViolationRule
+{
+ /// 违规类型(timeout / wrong_order / object_removed)
+ public string Type { get; set; } = "";
+
+ /// 描述(显示在告警横幅上)
+ public string Description { get; set; } = "";
+
+ /// 严重度
+ public int Severity { get; set; } = 1;
+}
+
+///
+/// 支持的违规类型(参考项目枚举 8 项里真正有实现、且配方真用过的)
+///
+public static class ViolationType
+{
+ /// 本步超时
+ public const string Timeout = "timeout";
+
+ /// 错序 / 跳步
+ public const string WrongOrder = "wrong_order";
+
+ /// must_keep 的物体被拿走
+ public const string ObjectRemoved = "object_removed";
+}
diff --git a/src/SopHelper.Engine/Sop/SopConfigLoader.cs b/src/SopHelper.Engine/Sop/SopConfigLoader.cs
new file mode 100644
index 0000000..8363f06
--- /dev/null
+++ b/src/SopHelper.Engine/Sop/SopConfigLoader.cs
@@ -0,0 +1,129 @@
+using System.Text.RegularExpressions;
+using YamlDotNet.Serialization;
+using YamlDotNet.Serialization.NamingConventions;
+
+namespace SopHelper.Engine.Sop;
+
+///
+/// 配方加载器:YAML → SopConfig,并做可用性校验(校验结果进 Warnings,界面要显示)。
+///
+public static partial class SopConfigLoader
+{
+ ///
+ /// 读一个配方文件
+ ///
+ public static SopConfig Load(string yamlPath)
+ {
+ var config = Parse(File.ReadAllText(yamlPath));
+
+ if (string.IsNullOrWhiteSpace(config.Sop.Name))
+ config.Warnings.Add("配方缺少 sop.name");
+
+ return config;
+ }
+
+ ///
+ /// 从 YAML 文本解析(与 Load 同一套校验,便于单测)
+ ///
+ public static SopConfig Parse(string yaml)
+ {
+ var deserializer = new DeserializerBuilder()
+ .WithNamingConvention(UnderscoredNamingConvention.Instance)
+ .WithCaseInsensitivePropertyMatching()
+ .IgnoreUnmatchedProperties()
+ .Build();
+
+ var config = deserializer.Deserialize(yaml) ?? new SopConfig();
+
+ Validate(config);
+
+ return config;
+ }
+
+ ///
+ /// 校验:配方里写了引擎没实现的方法,一定要在这里报出来,
+ /// 否则现场表现是"这一步永远不推进",极难定位。
+ ///
+ private static void Validate(SopConfig config)
+ {
+ var supported = new HashSet(StringComparer.OrdinalIgnoreCase)
+ {
+ ConditionMethod.ObjectPresent,
+ ConditionMethod.ObjectInZone,
+ ConditionMethod.HandInRegion,
+ ConditionMethod.HandMove,
+ ConditionMethod.HandAction,
+ ConditionMethod.HandNearObject,
+ ConditionMethod.PersonPresent,
+ ConditionMethod.TimeElapsed,
+ };
+
+ var regionNames = new HashSet(config.Sop.Regions.Keys, StringComparer.OrdinalIgnoreCase);
+
+ if (config.Sop.Steps.Count == 0)
+ config.Warnings.Add("配方没有任何步骤");
+
+ // 起始步骤取最小 Id(配方步骤不固定从 1 开始)
+ var ordered = config.Sop.Steps.OrderBy(s => s.Id).ToList();
+ if (ordered.Count > 0 && ordered[0].Id != config.Sop.Steps.Min(s => s.Id))
+ config.Warnings.Add("步骤顺序与 Id 不一致,执行顺序按 Id 升序");
+
+ foreach (var step in ordered)
+ {
+ var condition = step.Detection;
+ if (condition is null)
+ {
+ config.Warnings.Add($"步骤 {step.Id}({step.Name})没有 detection 节点,只能靠超时推进");
+ continue;
+ }
+
+ if (!supported.Contains(condition.Method))
+ {
+ config.Warnings.Add(
+ $"步骤 {step.Id} 的方法 '{condition.Method}' 本骨架未实现(支持:{string.Join(", ", supported)}),该条件视为不满足");
+ }
+
+ // 区域引用检查(区域没标定 → 现场就是不推进)
+ foreach (var name in new[] { condition.Region, condition.FromRegion, condition.ToRegion })
+ {
+ if (string.IsNullOrWhiteSpace(name)) continue;
+
+ if (!regionNames.Contains(name))
+ config.Warnings.Add($"步骤 {step.Id} 引用了未定义的区域 '{name}'");
+ }
+
+ if (NeedsModel(condition.Method) && config.Sop.Model is null)
+ config.Warnings.Add($"步骤 {step.Id} 的方法 '{condition.Method}' 需要模型,但配方没写 sop.model");
+
+ foreach (var rule in step.ViolationRules)
+ {
+ if (rule.Type.Equals(ViolationType.Timeout, StringComparison.OrdinalIgnoreCase)
+ && step.Timeout <= 0)
+ {
+ config.Warnings.Add($"步骤 {step.Id} 配了超时违规但 timeout=0,不会触发");
+ }
+ }
+ }
+
+ // 没有模型时,靠模型的条件全部无法判定
+ if (config.Sop.Model is null)
+ {
+ var needsModel = config.Sop.Steps.Any(s => s.Detection is not null && NeedsModel(s.Detection.Method));
+ if (needsModel)
+ config.Warnings.Add("配方需要检测模型但未配置 sop.model —— 只有手部与计时类条件能工作");
+ }
+ }
+
+ ///
+ /// 该方法是否依赖 YOLO 模型。手部类(hand_in_region / hand_move / hand_action)
+ /// 与计时只用 MediaPipe,不在此列;hand_near_object 要比对物体,算依赖。
+ ///
+ private static bool NeedsModel(string method) => method.ToLowerInvariant() switch
+ {
+ ConditionMethod.ObjectPresent => true,
+ ConditionMethod.ObjectInZone => true,
+ ConditionMethod.PersonPresent => true,
+ ConditionMethod.HandNearObject => true,
+ _ => false,
+ };
+}
diff --git a/src/SopHelper.Engine/Sop/SopEngine.cs b/src/SopHelper.Engine/Sop/SopEngine.cs
new file mode 100644
index 0000000..b463765
--- /dev/null
+++ b/src/SopHelper.Engine/Sop/SopEngine.cs
@@ -0,0 +1,267 @@
+using SopHelper.Engine.Common;
+
+namespace SopHelper.Engine.Sop;
+
+///
+/// 一次运行日志
+///
+public class LogEntry
+{
+ /// 时刻
+ public DateTime At { get; set; } = DateTime.Now;
+
+ /// 级别:info / warn / viol
+ public string Level { get; set; } = "info";
+
+ /// 文案
+ public string Message { get; set; } = "";
+}
+
+///
+/// 运行状态
+///
+public enum EngineState
+{
+ /// 未加载配方
+ Idle = 0,
+
+ /// 运行中
+ Running = 1,
+
+ /// 暂停
+ Paused = 2,
+
+ /// 整轮完成
+ Completed = 3,
+}
+
+///
+/// SOP 状态机:加载配方 → 逐步判定 → 违规 → 日志。
+/// 判定和日志都在这一层,UI 只订阅事件(引擎层不引用任何 WPF 类型)。
+///
+public class SopEngine
+{
+ private SopConfig _config = new();
+ private ConditionEvaluator _evaluator = null!;
+ private ViolationDetector _violations = null!;
+
+ private readonly Dictionary _regions = new(StringComparer.OrdinalIgnoreCase);
+ private List _ordered = [];
+
+ private int _index;
+ private DateTime _stepEnteredAt = DateTime.Now;
+
+ /// 当前运行状态
+ public EngineState State { get; private set; } = EngineState.Idle;
+
+ /// 当前步骤(未完成的那一步)
+ public StepDef? CurrentStep => State is EngineState.Idle or EngineState.Completed ? null : StepAt(_index);
+
+ /// 配方(UI 显示步骤卡用)
+ public SopConfig Config => _config;
+
+ /// 每帧判定后的步骤状态快照(UI 步骤卡数据源)
+ public event Action? StepSnapshotChanged;
+
+ /// 违规(Top3 横幅数据源)
+ public event Action? ViolationRaised;
+
+ /// 日志
+ public event Action? LogArrived;
+
+ /// 整轮完成
+ public event Action? Completed;
+
+ ///
+ /// 加载配方(区域 → 像素矩形;校验提醒原样转出去)
+ ///
+ public void Load(SopConfig config)
+ {
+ _config = config;
+
+ _regions.Clear();
+ foreach (var (name, def) in config.Sop.Regions)
+ _regions[name] = new DetRect(def.X1, def.Y1, def.X2 - def.X1, def.Y2 - def.Y1);
+
+ _ordered = config.Sop.Steps.OrderBy(s => s.Id).ToList();
+
+ _evaluator = new ConditionEvaluator(config.Sop.Settings, _regions);
+ _violations = new ViolationDetector(config.Sop.Settings);
+ _violations.SetRegions(_regions);
+
+ State = EngineState.Idle;
+ _index = 0;
+
+ foreach (var warning in config.Warnings)
+ Log("warn", warning);
+ }
+
+ ///
+ /// 开始运行(必须已 Load 配方)
+ ///
+ public void Start()
+ {
+ if (_ordered.Count == 0)
+ {
+ Log("warn", "配方没有步骤,无法开始");
+ return;
+ }
+
+ // Start 必须清空跨帧状态,否则新一轮会"秒过"绕过防抖(参考项目同款要求)
+ _evaluator.Reset();
+ _violations.Reset();
+
+ _index = 0;
+ _stepEnteredAt = DateTime.Now;
+ _evaluator.NoteStepEntered(_ordered[0].Id, _stepEnteredAt);
+
+ State = EngineState.Running;
+ Log("info", $"开始运行:{_config.Sop.Name}({_ordered.Count} 步)");
+ NotifyCurrent();
+ }
+
+ ///
+ /// 复位
+ ///
+ public void Reset()
+ {
+ _evaluator.Reset();
+ _violations.Reset();
+
+ _index = 0;
+ _stepEnteredAt = DateTime.Now;
+
+ State = EngineState.Running;
+ Log("info", "已复位");
+ NotifyCurrent();
+ }
+
+ ///
+ /// 暂停 / 继续
+ ///
+ public void TogglePause()
+ {
+ if (State == EngineState.Running)
+ {
+ State = EngineState.Paused;
+ Log("info", "已暂停");
+ }
+ else if (State == EngineState.Paused)
+ {
+ State = EngineState.Running;
+ Log("info", "已继续");
+ }
+ }
+
+ ///
+ /// 一帧的判定入口(管线回调)
+ ///
+ public void ProcessFrame(FrameResult frame)
+ {
+ if (State != EngineState.Running) return;
+
+ var step = StepAt(_index);
+ if (step is null) return;
+
+ // 1. 先判定完成条件(稳定帧门控在 evaluator 里)——
+ // 必须先判:本帧当前步也可能刚好达成,那样就不算跳步
+ var result = _evaluator.EvaluateStep(step, frame);
+
+ // 2. 违规:超时 / 必留物被拿走 / 跳步
+ var violation = _violations.CheckTimeout(step, _stepEnteredAt)
+ ?? _violations.CheckMustKeep(step, frame)
+ ?? (result.IsMet ? null : _violations.CheckSkip(step, StepAt(_index + 1), result.IsMet, frame));
+
+ if (violation is not null)
+ {
+ ViolationRaised?.Invoke(violation);
+ Log("viol", violation.Message);
+ }
+
+
+ var snapshot = new StepSnapshot
+ {
+ StepId = step.Id,
+ Name = step.Name,
+ IsCurrent = true,
+ IsMet = result.IsMet,
+ Message = result.Message,
+ };
+
+ StepSnapshotChanged?.Invoke(snapshot);
+
+ if (!result.IsMet) return;
+
+ Log("info", $"✓ 步骤 {step.Id}「{step.Name}」完成 — {result.Message}");
+
+ // 3. 推进
+ _index++;
+
+ if (_index >= _ordered.Count)
+ {
+ State = EngineState.Completed;
+ Log("info", "★ 全部步骤完成");
+ Completed?.Invoke();
+ NotifyCurrent();
+
+ if (_config.Sop.Settings.AutoResetOnComplete)
+ {
+ // 停留一会儿让操作员看到结果,再自动复位
+ Task.Delay(TimeSpan.FromSeconds(Math.Max(1, _config.Sop.Settings.ResetDelaySec)))
+ .ContinueWith(_ => Reset());
+ }
+
+ return;
+ }
+
+ _stepEnteredAt = DateTime.Now;
+ _evaluator.NoteStepEntered(_ordered[_index].Id, _stepEnteredAt);
+ NotifyCurrent();
+ }
+
+ private StepDef? StepAt(int index)
+ {
+ return index >= 0 && index < _ordered.Count ? _ordered[index] : null;
+ }
+
+ private void NotifyCurrent()
+ {
+ var step = CurrentStep;
+ if (step is null) return;
+
+ StepSnapshotChanged?.Invoke(new StepSnapshot
+ {
+ StepId = step.Id,
+ Name = step.Name,
+ IsCurrent = true,
+ IsMet = false,
+ Message = State == EngineState.Running ? "等待判定…" : "已复位",
+ });
+ }
+
+ private void Log(string level, string message)
+ {
+ LogArrived?.Invoke(new LogEntry { Level = level, Message = message });
+ }
+}
+
+///
+/// 步骤状态快照(UI 步骤卡数据源)
+///
+public class StepSnapshot
+{
+ /// 步骤 Id
+ public int StepId { get; set; }
+
+ /// 步骤名
+ public string Name { get; set; } = "";
+
+ /// 是否当前步骤
+ public bool IsCurrent { get; set; }
+
+ /// 条件是否已满足
+ public bool IsMet { get; set; }
+
+ /// 判定说明
+ public string Message { get; set; } = "";
+}
diff --git a/src/SopHelper.Engine/Sop/ViolationDetector.cs b/src/SopHelper.Engine/Sop/ViolationDetector.cs
new file mode 100644
index 0000000..7f0956d
--- /dev/null
+++ b/src/SopHelper.Engine/Sop/ViolationDetector.cs
@@ -0,0 +1,199 @@
+using SopHelper.Engine.Common;
+
+namespace SopHelper.Engine.Sop;
+
+///
+/// 一次违规事件
+///
+public class ViolationEvent
+{
+ /// 发生的步骤 Id
+ public int StepId { get; set; }
+
+ /// 违规类型(ViolationType)
+ public string Type { get; set; } = "";
+
+ /// 严重度
+ public int Severity { get; set; } = 1;
+
+ /// 说明(告警横幅文案)
+ public string Message { get; set; } = "";
+
+ /// 发生时刻
+ public DateTime At { get; set; } = DateTime.Now;
+}
+
+///
+/// 违规判定:超时 / 跳步(错序)/ 必留物被拿走。
+/// 每类违规带冷却,避免逐帧刷屏(参考项目用 3s,这里保持一致)。
+///
+public class ViolationDetector
+{
+ /// 同类违规最小间隔
+ private static readonly TimeSpan Cooldown = TimeSpan.FromSeconds(3);
+
+ private readonly SopSettings _settings;
+ private readonly Dictionary _regions = [];
+ private readonly Dictionary _lastFired = [];
+
+ /// 每个必留物体最近一次被检出的时刻(判"被拿走"用)
+ private readonly Dictionary _lastSeenObject = new(StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// 违规判定
+ ///
+ public ViolationDetector(SopSettings settings)
+ {
+ _settings = settings;
+ }
+
+ ///
+ /// 清空跨帧状态(工作流 Start/Reset 时调用)
+ ///
+ public void Reset()
+ {
+ _lastFired.Clear();
+ _lastSeenObject.Clear();
+ }
+
+ ///
+ /// 本步超时
+ ///
+ public ViolationEvent? CheckTimeout(StepDef step, DateTime stepEnteredAt)
+ {
+ if (!_settings.EnableTimeoutDetection) return null;
+ if (step.Timeout <= 0) return null;
+
+ var elapsed = DateTime.Now - stepEnteredAt;
+ if (elapsed.TotalSeconds < step.Timeout) return null;
+
+ var rule = FindRule(step, ViolationType.Timeout);
+
+ return Fire(rule, step.Id, $"步骤 {step.Id}「{step.Name}」超时 {elapsed.TotalSeconds:F0}s(限 {step.Timeout}s)");
+ }
+
+ ///
+ /// 跳步:下一部的条件已满足,但当前步骤还没完成。
+ /// 只看紧邻的下一步(参考项目的实测结论:看更远会大量误报)。
+ ///
+ public ViolationEvent? CheckSkip(StepDef current, StepDef? next, bool currentMet, FrameResult frame)
+ {
+ if (!_settings.EnableSkipDetection) return null;
+ if (next is null) return null;
+ if (currentMet) return null;
+ if (next.Detection is null) return null;
+
+ var rule = FindRule(current, ViolationType.WrongOrder);
+
+ var nextMet = QuickEvaluate(next, frame);
+ if (!nextMet) return null;
+
+ return Fire(rule, current.Id, $"跳步:步骤 {current.Id}「{current.Name}」未完成,却已满足步骤 {next.Id}「{next.Name}」");
+ }
+
+ ///
+ /// 必留物被拿走:本步期间 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 bool QuickEvaluate(StepDef step, FrameResult frame)
+ {
+ var condition = step.Detection!;
+ var conf = condition.MinConfidence > 0 ? condition.MinConfidence : _settings.ConfidenceThreshold;
+ var tolerance = condition.Tolerance > 0 ? condition.Tolerance : _settings.PositionTolerance;
+
+ switch (condition.Method.ToLowerInvariant())
+ {
+ case ConditionMethod.ObjectInZone:
+ {
+ var hit = frame.Detections.FirstOrDefault(d =>
+ d.Label.Equals(condition.TargetObject, StringComparison.OrdinalIgnoreCase) && d.Confidence >= conf);
+
+ if (hit is null) return false;
+
+ var (cx, cy) = hit.Rect.Center;
+ return Regions().TryGetValue(condition.Region, out var rect) && rect.Contains(cx, cy, tolerance);
+ }
+
+ case ConditionMethod.HandInRegion:
+ {
+ if (frame.Hands.Count == 0) return false;
+ var (hx, hy) = frame.Hands[0].Center;
+
+ return Regions().TryGetValue(condition.Region, out var rect) && rect.Contains(hx, hy, tolerance);
+ }
+
+ default:
+ return false;
+ }
+ }
+
+ private Dictionary Regions() => _regions;
+
+ ///
+ /// 区域字典由引擎注入(跳步判定要看区域坐标)
+ ///
+ public void SetRegions(Dictionary regions)
+ {
+ _regions.Clear();
+
+ foreach (var (key, value) in regions)
+ _regions[key] = value;
+ }
+
+ private static ViolationRule? FindRule(StepDef step, string type)
+ {
+ return step.ViolationRules.FirstOrDefault(r => r.Type.Equals(type, StringComparison.OrdinalIgnoreCase));
+ }
+
+ private ViolationEvent? Fire(ViolationRule? rule, int stepId, string message)
+ {
+ var type = rule?.Type ?? ViolationType.Timeout;
+
+ if (_lastFired.TryGetValue(type, out var last) && DateTime.Now - last < Cooldown)
+ return null;
+
+ _lastFired[type] = DateTime.Now;
+
+ return new ViolationEvent
+ {
+ StepId = stepId,
+ Type = type,
+ Severity = rule?.Severity ?? 1,
+ Message = string.IsNullOrWhiteSpace(rule?.Description) ? message : rule!.Description,
+ };
+ }
+}