feat(Engine): SOP 引擎 — 配方 YAML 加载/校验 + 条件判定 + 违规 + 状态机
- 配方 schema 沿用参考项目(sop/settings/regions/steps),现有 YAML 可直接搬 - 只实现其配方里真被用过的 8 个方法,未实现的在加载期就报出来 - 稳定帧门控按 (步骤Id,条件序号) 计数,time_elapsed/hand_move/hand_action 豁免 - 违规:超时/跳步(仅看紧邻下一步)/必留物被拿走,同类 3s 冷却 - 引擎层只用自有 DetRect,不引用任何 WPF 类型,事件解耦给 UI - configs/sop/demo.yaml: 不依赖检测模型的最小闭环示例
This commit is contained in:
parent
061b8cd3be
commit
b75684b254
108
configs/sop/demo.yaml
Normal file
108
configs/sop/demo.yaml
Normal file
@ -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
|
||||
328
src/SopHelper.Engine/Sop/ConditionEvaluator.cs
Normal file
328
src/SopHelper.Engine/Sop/ConditionEvaluator.cs
Normal file
@ -0,0 +1,328 @@
|
||||
using SopHelper.Engine.Common;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
/// <summary>
|
||||
/// 条件判定结果
|
||||
/// </summary>
|
||||
public class ConditionResult
|
||||
{
|
||||
/// <summary>是否满足</summary>
|
||||
public bool IsMet { get; set; }
|
||||
|
||||
/// <summary>说明(不满足时给出原因,界面直接显示)</summary>
|
||||
public string Message { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 单条件判定 + 稳定帧门控。
|
||||
/// 门控语义照搬参考项目(它自己踩过坑):按 (步骤Id, 条件序号) 累计连续命中帧数,
|
||||
/// 达标才放行;未命中即清零;Start/Reset 必须清空,否则新一轮会"秒过"绕过防抖。
|
||||
/// </summary>
|
||||
public class ConditionEvaluator
|
||||
{
|
||||
private readonly SopSettings _settings;
|
||||
private readonly Dictionary<string, DetRect> _regions;
|
||||
|
||||
/// <summary>稳定帧计数:key = "步骤Id:条件序号"</summary>
|
||||
private readonly Dictionary<string, int> _stablePassCounts = [];
|
||||
|
||||
/// <summary>每只手最近访问过的区域(hand_move 的 from 证据)</summary>
|
||||
private readonly Dictionary<string, HashSet<string>> _handVisitedRegions = [];
|
||||
|
||||
/// <summary>每个物体最近访问过的区域(手搬运物体时,from 证据来自物体轨迹)</summary>
|
||||
private readonly Dictionary<string, HashSet<string>> _objectVisitedRegions = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>步骤进入时刻(time_elapsed 用)</summary>
|
||||
private readonly Dictionary<int, DateTime> _stepEnterTime = [];
|
||||
|
||||
/// <summary>
|
||||
/// 单条件判定 + 稳定帧门控
|
||||
/// </summary>
|
||||
public ConditionEvaluator(SopSettings settings, Dictionary<string, DetRect> regions)
|
||||
{
|
||||
_settings = settings;
|
||||
_regions = regions;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 步骤进入时登记时刻(引擎在推进步骤时调用)
|
||||
/// </summary>
|
||||
public void NoteStepEntered(int stepId, DateTime now)
|
||||
{
|
||||
_stepEnterTime.TryAdd(stepId, now);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清空跨帧状态(工作流 Start/Reset 时调用)
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
_stablePassCounts.Clear();
|
||||
_handVisitedRegions.Clear();
|
||||
_objectVisitedRegions.Clear();
|
||||
_stepEnterTime.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判定一个步骤的全部条件(AND 短路:一个步骤 = 一个检测节点,多个条件全满足才过)
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 单条方法的判定(不含门控)
|
||||
/// </summary>
|
||||
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}' 未实现");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 稳定帧门控。time_elapsed / hand_move / hand_action 豁免
|
||||
/// (自带时序或瞬时交互语义,与参考项目的豁免清单一致)。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 记录本帧的轨迹证据(下一帧才用得上)
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// from 区证据:物体轨迹优先(搬运),没有就看手自己的轨迹
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取判定用的手。hand:any 优先右手(与参考项目一致)
|
||||
/// </summary>
|
||||
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],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按类别找检测框(取置信度最高的那个)
|
||||
/// </summary>
|
||||
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 };
|
||||
}
|
||||
248
src/SopHelper.Engine/Sop/SopConfig.cs
Normal file
248
src/SopHelper.Engine/Sop/SopConfig.cs
Normal file
@ -0,0 +1,248 @@
|
||||
using YamlDotNet.Serialization;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
/// <summary>
|
||||
/// SOP 配方(YAML 反序列化根)。字段名保持与参考项目一致,现有配方文件可直接搬。
|
||||
/// </summary>
|
||||
public class SopConfig
|
||||
{
|
||||
/// <summary>sop 根节点</summary>
|
||||
public SopBody Sop { get; set; } = new();
|
||||
|
||||
/// <summary>加载过程中的提醒(缺字段、未知方法等,界面要显示)</summary>
|
||||
[YamlIgnore]
|
||||
public List<string> Warnings { get; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// sop 节点
|
||||
/// </summary>
|
||||
public class SopBody
|
||||
{
|
||||
/// <summary>配方名</summary>
|
||||
public string Name { get; set; } = "";
|
||||
|
||||
/// <summary>版本</summary>
|
||||
public string Version { get; set; } = "1.0";
|
||||
|
||||
/// <summary>说明</summary>
|
||||
public string Description { get; set; } = "";
|
||||
|
||||
/// <summary>全局设置</summary>
|
||||
public SopSettings Settings { get; set; } = new();
|
||||
|
||||
/// <summary>区域定义(键 = 配方里引用的区域名)</summary>
|
||||
public Dictionary<string, RegionDef> Regions { get; set; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>步骤列表(按书写顺序执行)</summary>
|
||||
public List<StepDef> Steps { get; set; } = [];
|
||||
|
||||
/// <summary>默认模型(缺省=只做手部与计时;写了就跑 YOLO)</summary>
|
||||
public ModelDef? Model { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// sop.settings
|
||||
/// </summary>
|
||||
public class SopSettings
|
||||
{
|
||||
/// <summary>全局置信度阈值</summary>
|
||||
public float ConfidenceThreshold { get; set; } = 0.6f;
|
||||
|
||||
/// <summary>默认稳定帧数(条件未写 stable_frames 时用它)</summary>
|
||||
public int StableFrames { get; set; } = 5;
|
||||
|
||||
/// <summary>区域命中容差(像素)</summary>
|
||||
public float PositionTolerance { get; set; } = 20f;
|
||||
|
||||
/// <summary>启用超时违规</summary>
|
||||
public bool EnableTimeoutDetection { get; set; } = true;
|
||||
|
||||
/// <summary>启用跳步/错序违规</summary>
|
||||
public bool EnableSkipDetection { get; set; } = true;
|
||||
|
||||
/// <summary>整轮完成后自动复位</summary>
|
||||
public bool AutoResetOnComplete { get; set; } = true;
|
||||
|
||||
/// <summary>复位前停留秒数</summary>
|
||||
public int ResetDelaySec { get; set; } = 1;
|
||||
|
||||
/// <summary>抽帧间隔(1=每帧都判;推理跟不上时调大可稳住帧率)</summary>
|
||||
public int FrameStride { get; set; } = 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 区域定义(绝对像素坐标,须在真机画面上标定)
|
||||
/// </summary>
|
||||
public class RegionDef
|
||||
{
|
||||
/// <summary>左上 X</summary>
|
||||
public int X1 { get; set; }
|
||||
|
||||
/// <summary>左上 Y</summary>
|
||||
public int Y1 { get; set; }
|
||||
|
||||
/// <summary>右下 X</summary>
|
||||
public int X2 { get; set; }
|
||||
|
||||
/// <summary>右下 Y</summary>
|
||||
public int Y2 { get; set; }
|
||||
|
||||
/// <summary>区域名(显示用)</summary>
|
||||
public string Name { get; set; } = "";
|
||||
|
||||
/// <summary>说明</summary>
|
||||
public string Description { get; set; } = "";
|
||||
|
||||
/// <summary>显示颜色</summary>
|
||||
public string Color { get; set; } = "#4CAF50";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模型定义
|
||||
/// </summary>
|
||||
public class ModelDef
|
||||
{
|
||||
/// <summary>onnx 路径(相对程序目录)</summary>
|
||||
public string Path { get; set; } = "";
|
||||
|
||||
/// <summary>类别名,顺序必须与训练时一致</summary>
|
||||
public List<string> Classes { get; set; } = [];
|
||||
|
||||
/// <summary>输入尺寸</summary>
|
||||
public int InputSize { get; set; } = 640;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 步骤定义
|
||||
/// </summary>
|
||||
public class StepDef
|
||||
{
|
||||
/// <summary>步骤号(不必从 1 开始,状态机取最小值起步)</summary>
|
||||
public int Id { get; set; }
|
||||
|
||||
/// <summary>步骤名</summary>
|
||||
public string Name { get; set; } = "";
|
||||
|
||||
/// <summary>说明</summary>
|
||||
public string Description { get; set; } = "";
|
||||
|
||||
/// <summary>本步超时秒数(0 = 不限制)</summary>
|
||||
public int Timeout { get; set; }
|
||||
|
||||
/// <summary>标准节拍毫秒(报表对比用,判定不参与)</summary>
|
||||
public int StandardDurationMs { get; set; }
|
||||
|
||||
/// <summary>本步判定条件(AND,全部满足才算完成)</summary>
|
||||
public StepCondition? Detection { get; set; }
|
||||
|
||||
/// <summary>本步期间必须常在的物体,被拿走即违规</summary>
|
||||
public List<string> MustKeep { get; set; } = [];
|
||||
|
||||
/// <summary>本步完成时必须存在的物体(漏放/缺料)</summary>
|
||||
public List<string> RequiredObjects { get; set; } = [];
|
||||
|
||||
/// <summary>违规规则</summary>
|
||||
public List<ViolationRule> ViolationRules { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 步骤判定条件
|
||||
/// </summary>
|
||||
public class StepCondition
|
||||
{
|
||||
/// <summary>判定方法(见 ConditionMethod)</summary>
|
||||
public string Method { get; set; } = "";
|
||||
|
||||
/// <summary>目标物体类别(物体类条件用)</summary>
|
||||
public string TargetObject { get; set; } = "";
|
||||
|
||||
/// <summary>主区域名</summary>
|
||||
public string Region { get; set; } = "";
|
||||
|
||||
/// <summary>起点区域名(hand_move 的 from)</summary>
|
||||
public string FromRegion { get; set; } = "";
|
||||
|
||||
/// <summary>终点区域名(hand_move 的 to)</summary>
|
||||
public string ToRegion { get; set; } = "";
|
||||
|
||||
/// <summary>手:left / right / any</summary>
|
||||
public string Hand { get; set; } = "any";
|
||||
|
||||
/// <summary>手-物相邻容差(像素)</summary>
|
||||
public float Tolerance { get; set; } = 60f;
|
||||
|
||||
/// <summary>本条件置信度阈值</summary>
|
||||
public float MinConfidence { get; set; } = 0.7f;
|
||||
|
||||
/// <summary>稳定帧数(连续命中才放行)</summary>
|
||||
public int StableFrames { get; set; } = 5;
|
||||
|
||||
/// <summary>计时毫秒(time_elapsed 用)</summary>
|
||||
public int DurationMs { get; set; }
|
||||
|
||||
/// <summary>动作语义(hand_action 用:pickup / putdown)</summary>
|
||||
public string Action { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 配方支持的条件方法。只列参考项目配方里真被用过的(按其统计覆盖其 90% 实际用法),
|
||||
/// 没实现的枚举成员一律不写进配方示例。
|
||||
/// </summary>
|
||||
public static class ConditionMethod
|
||||
{
|
||||
/// <summary>目标出现在画面(1 次)</summary>
|
||||
public const string ObjectPresent = "object_present";
|
||||
|
||||
/// <summary>目标在区域内(14 次,第二常用)</summary>
|
||||
public const string ObjectInZone = "object_in_zone";
|
||||
|
||||
/// <summary>手在区域内(12 次)</summary>
|
||||
public const string HandInRegion = "hand_in_region";
|
||||
|
||||
/// <summary>手从 A 区移到 B 区(7 次;配方里写作 hand_move)</summary>
|
||||
public const string HandMove = "hand_move";
|
||||
|
||||
/// <summary>取放动作(10 次;= hand_move + 动作语义)</summary>
|
||||
public const string HandAction = "hand_action";
|
||||
|
||||
/// <summary>手-物相邻(3 次)</summary>
|
||||
public const string HandNearObject = "hand_near_object";
|
||||
|
||||
/// <summary>人在场(7 次,走 COCO 的 person)</summary>
|
||||
public const string PersonPresent = "person_present";
|
||||
|
||||
/// <summary>持续计时(16 次,最常用)</summary>
|
||||
public const string TimeElapsed = "time_elapsed";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 违规规则
|
||||
/// </summary>
|
||||
public class ViolationRule
|
||||
{
|
||||
/// <summary>违规类型(timeout / wrong_order / object_removed)</summary>
|
||||
public string Type { get; set; } = "";
|
||||
|
||||
/// <summary>描述(显示在告警横幅上)</summary>
|
||||
public string Description { get; set; } = "";
|
||||
|
||||
/// <summary>严重度</summary>
|
||||
public int Severity { get; set; } = 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 支持的违规类型(参考项目枚举 8 项里真正有实现、且配方真用过的)
|
||||
/// </summary>
|
||||
public static class ViolationType
|
||||
{
|
||||
/// <summary>本步超时</summary>
|
||||
public const string Timeout = "timeout";
|
||||
|
||||
/// <summary>错序 / 跳步</summary>
|
||||
public const string WrongOrder = "wrong_order";
|
||||
|
||||
/// <summary>must_keep 的物体被拿走</summary>
|
||||
public const string ObjectRemoved = "object_removed";
|
||||
}
|
||||
129
src/SopHelper.Engine/Sop/SopConfigLoader.cs
Normal file
129
src/SopHelper.Engine/Sop/SopConfigLoader.cs
Normal file
@ -0,0 +1,129 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using YamlDotNet.Serialization;
|
||||
using YamlDotNet.Serialization.NamingConventions;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
/// <summary>
|
||||
/// 配方加载器:YAML → SopConfig,并做可用性校验(校验结果进 Warnings,界面要显示)。
|
||||
/// </summary>
|
||||
public static partial class SopConfigLoader
|
||||
{
|
||||
/// <summary>
|
||||
/// 读一个配方文件
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 YAML 文本解析(与 Load 同一套校验,便于单测)
|
||||
/// </summary>
|
||||
public static SopConfig Parse(string yaml)
|
||||
{
|
||||
var deserializer = new DeserializerBuilder()
|
||||
.WithNamingConvention(UnderscoredNamingConvention.Instance)
|
||||
.WithCaseInsensitivePropertyMatching()
|
||||
.IgnoreUnmatchedProperties()
|
||||
.Build();
|
||||
|
||||
var config = deserializer.Deserialize<SopConfig>(yaml) ?? new SopConfig();
|
||||
|
||||
Validate(config);
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 校验:配方里写了引擎没实现的方法,一定要在这里报出来,
|
||||
/// 否则现场表现是"这一步永远不推进",极难定位。
|
||||
/// </summary>
|
||||
private static void Validate(SopConfig config)
|
||||
{
|
||||
var supported = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
ConditionMethod.ObjectPresent,
|
||||
ConditionMethod.ObjectInZone,
|
||||
ConditionMethod.HandInRegion,
|
||||
ConditionMethod.HandMove,
|
||||
ConditionMethod.HandAction,
|
||||
ConditionMethod.HandNearObject,
|
||||
ConditionMethod.PersonPresent,
|
||||
ConditionMethod.TimeElapsed,
|
||||
};
|
||||
|
||||
var regionNames = new HashSet<String>(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 —— 只有手部与计时类条件能工作");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 该方法是否依赖 YOLO 模型。手部类(hand_in_region / hand_move / hand_action)
|
||||
/// 与计时只用 MediaPipe,不在此列;hand_near_object 要比对物体,算依赖。
|
||||
/// </summary>
|
||||
private static bool NeedsModel(string method) => method.ToLowerInvariant() switch
|
||||
{
|
||||
ConditionMethod.ObjectPresent => true,
|
||||
ConditionMethod.ObjectInZone => true,
|
||||
ConditionMethod.PersonPresent => true,
|
||||
ConditionMethod.HandNearObject => true,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
267
src/SopHelper.Engine/Sop/SopEngine.cs
Normal file
267
src/SopHelper.Engine/Sop/SopEngine.cs
Normal file
@ -0,0 +1,267 @@
|
||||
using SopHelper.Engine.Common;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
/// <summary>
|
||||
/// 一次运行日志
|
||||
/// </summary>
|
||||
public class LogEntry
|
||||
{
|
||||
/// <summary>时刻</summary>
|
||||
public DateTime At { get; set; } = DateTime.Now;
|
||||
|
||||
/// <summary>级别:info / warn / viol</summary>
|
||||
public string Level { get; set; } = "info";
|
||||
|
||||
/// <summary>文案</summary>
|
||||
public string Message { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 运行状态
|
||||
/// </summary>
|
||||
public enum EngineState
|
||||
{
|
||||
/// <summary>未加载配方</summary>
|
||||
Idle = 0,
|
||||
|
||||
/// <summary>运行中</summary>
|
||||
Running = 1,
|
||||
|
||||
/// <summary>暂停</summary>
|
||||
Paused = 2,
|
||||
|
||||
/// <summary>整轮完成</summary>
|
||||
Completed = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SOP 状态机:加载配方 → 逐步判定 → 违规 → 日志。
|
||||
/// 判定和日志都在这一层,UI 只订阅事件(引擎层不引用任何 WPF 类型)。
|
||||
/// </summary>
|
||||
public class SopEngine
|
||||
{
|
||||
private SopConfig _config = new();
|
||||
private ConditionEvaluator _evaluator = null!;
|
||||
private ViolationDetector _violations = null!;
|
||||
|
||||
private readonly Dictionary<string, DetRect> _regions = new(StringComparer.OrdinalIgnoreCase);
|
||||
private List<StepDef> _ordered = [];
|
||||
|
||||
private int _index;
|
||||
private DateTime _stepEnteredAt = DateTime.Now;
|
||||
|
||||
/// <summary>当前运行状态</summary>
|
||||
public EngineState State { get; private set; } = EngineState.Idle;
|
||||
|
||||
/// <summary>当前步骤(未完成的那一步)</summary>
|
||||
public StepDef? CurrentStep => State is EngineState.Idle or EngineState.Completed ? null : StepAt(_index);
|
||||
|
||||
/// <summary>配方(UI 显示步骤卡用)</summary>
|
||||
public SopConfig Config => _config;
|
||||
|
||||
/// <summary>每帧判定后的步骤状态快照(UI 步骤卡数据源)</summary>
|
||||
public event Action<StepSnapshot>? StepSnapshotChanged;
|
||||
|
||||
/// <summary>违规(Top3 横幅数据源)</summary>
|
||||
public event Action<ViolationEvent>? ViolationRaised;
|
||||
|
||||
/// <summary>日志</summary>
|
||||
public event Action<LogEntry>? LogArrived;
|
||||
|
||||
/// <summary>整轮完成</summary>
|
||||
public event Action? Completed;
|
||||
|
||||
/// <summary>
|
||||
/// 加载配方(区域 → 像素矩形;校验提醒原样转出去)
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开始运行(必须已 Load 配方)
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 复位
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
_evaluator.Reset();
|
||||
_violations.Reset();
|
||||
|
||||
_index = 0;
|
||||
_stepEnteredAt = DateTime.Now;
|
||||
|
||||
State = EngineState.Running;
|
||||
Log("info", "已复位");
|
||||
NotifyCurrent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 暂停 / 继续
|
||||
/// </summary>
|
||||
public void TogglePause()
|
||||
{
|
||||
if (State == EngineState.Running)
|
||||
{
|
||||
State = EngineState.Paused;
|
||||
Log("info", "已暂停");
|
||||
}
|
||||
else if (State == EngineState.Paused)
|
||||
{
|
||||
State = EngineState.Running;
|
||||
Log("info", "已继续");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一帧的判定入口(管线回调)
|
||||
/// </summary>
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 步骤状态快照(UI 步骤卡数据源)
|
||||
/// </summary>
|
||||
public class StepSnapshot
|
||||
{
|
||||
/// <summary>步骤 Id</summary>
|
||||
public int StepId { get; set; }
|
||||
|
||||
/// <summary>步骤名</summary>
|
||||
public string Name { get; set; } = "";
|
||||
|
||||
/// <summary>是否当前步骤</summary>
|
||||
public bool IsCurrent { get; set; }
|
||||
|
||||
/// <summary>条件是否已满足</summary>
|
||||
public bool IsMet { get; set; }
|
||||
|
||||
/// <summary>判定说明</summary>
|
||||
public string Message { get; set; } = "";
|
||||
}
|
||||
199
src/SopHelper.Engine/Sop/ViolationDetector.cs
Normal file
199
src/SopHelper.Engine/Sop/ViolationDetector.cs
Normal file
@ -0,0 +1,199 @@
|
||||
using SopHelper.Engine.Common;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
/// <summary>
|
||||
/// 一次违规事件
|
||||
/// </summary>
|
||||
public class ViolationEvent
|
||||
{
|
||||
/// <summary>发生的步骤 Id</summary>
|
||||
public int StepId { get; set; }
|
||||
|
||||
/// <summary>违规类型(ViolationType)</summary>
|
||||
public string Type { get; set; } = "";
|
||||
|
||||
/// <summary>严重度</summary>
|
||||
public int Severity { get; set; } = 1;
|
||||
|
||||
/// <summary>说明(告警横幅文案)</summary>
|
||||
public string Message { get; set; } = "";
|
||||
|
||||
/// <summary>发生时刻</summary>
|
||||
public DateTime At { get; set; } = DateTime.Now;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 违规判定:超时 / 跳步(错序)/ 必留物被拿走。
|
||||
/// 每类违规带冷却,避免逐帧刷屏(参考项目用 3s,这里保持一致)。
|
||||
/// </summary>
|
||||
public class ViolationDetector
|
||||
{
|
||||
/// <summary>同类违规最小间隔</summary>
|
||||
private static readonly TimeSpan Cooldown = TimeSpan.FromSeconds(3);
|
||||
|
||||
private readonly SopSettings _settings;
|
||||
private readonly Dictionary<string, DetRect> _regions = [];
|
||||
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>
|
||||
/// 清空跨帧状态(工作流 Start/Reset 时调用)
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
_lastFired.Clear();
|
||||
_lastSeenObject.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 本步超时
|
||||
/// </summary>
|
||||
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)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 跳步:下一部的条件已满足,但当前步骤还没完成。
|
||||
/// 只看紧邻的下一步(参考项目的实测结论:看更远会大量误报)。
|
||||
/// </summary>
|
||||
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}」");
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 轻量判定(只为跳步服务,不参与稳定帧门控,否则跳步永远不触发)
|
||||
/// </summary>
|
||||
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<string, DetRect> Regions() => _regions;
|
||||
|
||||
/// <summary>
|
||||
/// 区域字典由引擎注入(跳步判定要看区域坐标)
|
||||
/// </summary>
|
||||
public void SetRegions(Dictionary<string, DetRect> 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user