增加事件触发限时复检并在未通过时跳过继续
This commit is contained in:
parent
253bc2ea64
commit
11eaca66c6
@ -12,6 +12,7 @@ public class ConditionResult
|
||||
public int RequiredFrames { get; set; }
|
||||
/// <summary>是否满足</summary>
|
||||
public bool IsMet { get; set; }
|
||||
public bool IsSkipped { get; set; }
|
||||
|
||||
/// <summary>说明(不满足时给出原因,界面直接显示)</summary>
|
||||
public string Message { get; set; } = "";
|
||||
|
||||
@ -109,6 +109,7 @@ public static partial class SopConfigLoader
|
||||
config.Warnings.Add($"步骤 {step.Id} 的 AI 确认必须使用手进入区域、离开区域或区域间移动触发");
|
||||
if (!VisionImageMode.IsValid(ai)) config.Warnings.Add($"步骤 {step.Id} 的 AI 取图方式或手部范围参数无效");
|
||||
if (!VisionEvidenceMode.IsValid(ai)) config.Warnings.Add($"步骤 {step.Id} 的过程证据模式或观察窗口参数无效");
|
||||
if (!VisionEvidenceMode.IsCheckPolicyValid(ai)) config.Warnings.Add($"步骤 {step.Id} 的限时检查参数无效");
|
||||
if (VisionImageMode.Resolve(ai) == VisionImageMode.FixedRegion)
|
||||
{
|
||||
var region = config.Sop.Regions.FirstOrDefault(p => p.Key.Equals(ai.ImageRegion, StringComparison.OrdinalIgnoreCase)).Value;
|
||||
|
||||
@ -36,6 +36,7 @@ public partial class SopEngine
|
||||
_nextCaptureIndex = _index;
|
||||
_observationSequence = _lastCaptureSequence = 0;
|
||||
_observationWindows.Clear(); _acceptedEvidenceTimes.Clear();
|
||||
_continuousChecks.Clear();
|
||||
}
|
||||
|
||||
private static string? GetDecisionError(StepDef step)
|
||||
@ -43,7 +44,7 @@ public partial class SopEngine
|
||||
if (string.IsNullOrWhiteSpace(step.Description)) return "请先填写步骤说明,AI 将按说明判断是否完成";
|
||||
if (!ConditionMethod.SupportsAiTrigger(step.Detection?.Method)) return "AI 确认需要手进入、离开区域或区域间移动触发";
|
||||
var options = step.AiConfirmation ?? new();
|
||||
if (!VisionImageMode.IsValid(options) || !VisionEvidenceMode.IsValid(options) || !double.IsFinite(options.MinConfidence) || options.MinConfidence is < 0 or > 1
|
||||
if (!VisionImageMode.IsValid(options) || !VisionEvidenceMode.IsValid(options) || !VisionEvidenceMode.IsCheckPolicyValid(options) || !double.IsFinite(options.MinConfidence) || options.MinConfidence is < 0 or > 1
|
||||
|| options.RetryDelayMs < 0 || options.TimeoutSeconds <= 0) return "AI 确认配置无效";
|
||||
return null;
|
||||
}
|
||||
@ -54,6 +55,8 @@ public partial class SopEngine
|
||||
evidence = null;
|
||||
if (GetDecisionError(step) is { } error) return new() { Message = error };
|
||||
var options = step.AiConfirmation ?? new();
|
||||
if (options.CheckWindowMs > 0)
|
||||
return EvaluateContinuousStep(step, frame, captureJpeg, captureDecisionImage, out evidence);
|
||||
if (options.EvidenceMode == VisionEvidenceMode.Sequence)
|
||||
return EvaluateObservationStep(step, frame, captureJpeg, captureDecisionImage, out evidence);
|
||||
_handImageRegion.Observe(step, frame, _regions);
|
||||
@ -190,6 +193,11 @@ public partial class SopEngine
|
||||
if (_nextCaptureIndex <= _index || _observationSequence <= _lastCaptureSequence
|
||||
|| _followingGate is not { } gate || StepAt(_nextCaptureIndex) is not { } step
|
||||
|| captureJpeg is null && captureDecisionImage is null || GetDecisionError(step) is not null) return;
|
||||
if (step.AiConfirmation?.CheckWindowMs > 0)
|
||||
{
|
||||
ObserveContinuousStep(_nextCaptureIndex, EnsureContinuousStep(_nextCaptureIndex, step, gate), frame, captureJpeg, captureDecisionImage);
|
||||
return;
|
||||
}
|
||||
if (step.AiConfirmation?.EvidenceMode == VisionEvidenceMode.Sequence)
|
||||
{
|
||||
if (VisionDecisionClient?.SupportsSequences != true) return;
|
||||
|
||||
@ -0,0 +1,146 @@
|
||||
using SopHelper.Engine.Common;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
public partial class SopEngine
|
||||
{
|
||||
private readonly Dictionary<int, ContinuousCheck> _continuousChecks = [];
|
||||
private sealed class ContinuousCheck(StepDef step, CaptureGate gate)
|
||||
{
|
||||
public StepDef Step = step;
|
||||
public CaptureGate Gate = gate;
|
||||
public ObservationEvidenceWindow Window = new(new AiConfirmation
|
||||
{
|
||||
ObservationPreRollMs = step.AiConfirmation!.ObservationPreRollMs,
|
||||
ObservationSampleMs = step.AiConfirmation.ObservationSampleMs,
|
||||
ObservationMinMs = step.AiConfirmation.ObservationMinMs,
|
||||
ObservationMaxMs = Math.Max(step.AiConfirmation.ObservationMaxMs, step.AiConfirmation.CheckWindowMs),
|
||||
ObservationMaxFrames = step.AiConfirmation.ObservationMaxFrames,
|
||||
});
|
||||
public bool Triggered;
|
||||
public long LastFrame = -1, StartedAt, LastSubmittedAt, FinishedAt;
|
||||
public double TriggerSeconds, LatestSeconds, LastMotionSeconds;
|
||||
public int Attempts, SentVersion;
|
||||
public Dictionary<HandType, (double X, double Y)> Anchors = [];
|
||||
public string Reason = "尚未获得检查结果";
|
||||
public double ElapsedMs => Math.Max((LatestSeconds - TriggerSeconds) * 1000, Environment.TickCount64 - StartedAt);
|
||||
}
|
||||
private ContinuousCheck EnsureContinuousStep(int index, StepDef step, CaptureGate gate)
|
||||
{
|
||||
if (_continuousChecks.TryGetValue(index, out var existing)) return existing;
|
||||
return _continuousChecks[index] = new(step, gate);
|
||||
}
|
||||
private void UpdateContinuousChecks(FrameResult frame, Func<byte[]>? capture, Func<RegionDef?, byte[]>? crop)
|
||||
{
|
||||
foreach (var pair in _continuousChecks.ToArray())
|
||||
if (pair.Key >= _index) ObserveContinuousStep(pair.Key, pair.Value, frame, capture, crop);
|
||||
}
|
||||
private void ObserveContinuousStep(int index, ContinuousCheck state, FrameResult frame,
|
||||
Func<byte[]>? capture, Func<RegionDef?, byte[]>? crop)
|
||||
{
|
||||
if (capture is null && crop is null || state.LastFrame == frame.FrameId) return;
|
||||
state.LastFrame = frame.FrameId;
|
||||
var seconds = frame.SourceSeconds ?? (frame.Timestamp - DateTime.UnixEpoch).TotalSeconds;
|
||||
state.LatestSeconds = seconds;
|
||||
var selected = frame.Hands.Where(h => state.Step.Detection?.Hand.ToLowerInvariant() switch
|
||||
{
|
||||
"left" or "左手" => h.HandType == HandType.Left,
|
||||
"right" or "右手" => h.HandType == HandType.Right,
|
||||
_ => true,
|
||||
}).GroupBy(h => h.HandType).ToDictionary(g => g.Key, g => ((double)g.First().Center.Cx, (double)g.First().Center.Cy));
|
||||
var movement = Math.Max(1, Math.Sqrt((double)frame.Size.W * frame.Size.W + (double)frame.Size.H * frame.Size.H) * .01);
|
||||
if (selected.Count != state.Anchors.Count || selected.Any(h => !state.Anchors.TryGetValue(h.Key, out var prior)
|
||||
|| Math.Sqrt(Math.Pow(h.Value.Item1 - prior.X, 2) + Math.Pow(h.Value.Item2 - prior.Y, 2)) > movement))
|
||||
{
|
||||
state.LastMotionSeconds = seconds; state.Anchors = selected;
|
||||
}
|
||||
var trigger = EvaluateCaptureGate(state.Step, frame, state.Gate, "continuous");
|
||||
if (!state.Triggered && trigger.IsMet)
|
||||
{
|
||||
state.Triggered = true; state.TriggerSeconds = seconds; state.StartedAt = Environment.TickCount64;
|
||||
state.LastMotionSeconds = seconds; state.Window.Open(seconds);
|
||||
Log("info", $"步骤 {state.Step.Id} 操作触发,打开 {state.Step.AiConfirmation!.CheckWindowMs}ms 检查窗口");
|
||||
// 跟踪立即向后推进,不等检查结束或模型返回;同一次区域停留仍受 RequireRelease 保护。
|
||||
if (_nextCaptureIndex == index) ArmFollowingStep(frame, state.Step);
|
||||
}
|
||||
if (state.Triggered && state.ElapsedMs >= state.Step.AiConfirmation!.CheckWindowMs) return;
|
||||
if (state.Window.WantsFrame(frame.FrameId, seconds))
|
||||
{
|
||||
var image = CaptureDecision(state.Step, frame, state.Gate.HandRegion, capture, crop, out var error, notify: false);
|
||||
if (image is not null) state.Window.Add(new(frame.FrameId, frame.Timestamp, image.Request.Jpeg, frame.SourceSeconds));
|
||||
else state.Reason = error ?? "取图失败";
|
||||
}
|
||||
state.Window.Advance(seconds);
|
||||
}
|
||||
private ConditionResult EvaluateContinuousStep(StepDef step, FrameResult frame, Func<byte[]>? capture,
|
||||
Func<RegionDef?, byte[]>? crop, out byte[]? evidence)
|
||||
{
|
||||
evidence = null;
|
||||
var options = step.AiConfirmation!;
|
||||
var gate = _nextCaptureIndex == _index && _followingGate is { } following ? following : new CaptureGate(_evaluator, _handImageRegion);
|
||||
var state = EnsureContinuousStep(_index, step, gate);
|
||||
ObserveContinuousStep(_index, state, frame, capture, crop);
|
||||
if (!state.Triggered) return new() { Message = "等待操作事件,保留触发前画面" };
|
||||
var expired = state.ElapsedMs >= options.CheckWindowMs;
|
||||
if (_pendingDecision is { } pending && pending.Task.IsCompleted)
|
||||
{
|
||||
_pendingDecision = null; pending.Cancellation.Dispose();
|
||||
var result = pending.Task.GetAwaiter().GetResult();
|
||||
var source = pending.Request.Frames ?? [];
|
||||
var completed = source.FirstOrDefault(f => f.FrameId == result.CompletionFrameId);
|
||||
var met = result.Completed && result.EffectiveStatus == VisionDecisionStatus.Completed
|
||||
&& double.IsFinite(result.Confidence) && result.Confidence >= options.MinConfidence && result.Confidence <= 1
|
||||
&& Volatile.Read(ref state.FinishedAt) - state.StartedAt <= options.CheckWindowMs
|
||||
&& (options.EvidenceMode == VisionEvidenceMode.SingleFrame || completed is not null
|
||||
&& result.EvidenceFrameIds is { Count: >= 2 } ids && ids.Distinct().Count() >= 2
|
||||
&& ids.Contains(completed.FrameId) && ids.All(id => source.Any(f => f.FrameId == id)));
|
||||
state.Reason = result.Reason;
|
||||
var evaluated = completed is not null && met ? pending.Request with
|
||||
{ FrameId = completed.FrameId, CapturedAt = completed.CapturedAt, Jpeg = completed.Jpeg, SourceSeconds = completed.SourceSeconds } : pending.Request;
|
||||
DecisionEvaluated?.Invoke(evaluated, result, met);
|
||||
if (met)
|
||||
{
|
||||
evidence = evaluated.Jpeg;
|
||||
_acceptedEvidenceTimes[_index] = evaluated.SourceSeconds ?? (evaluated.CapturedAt - DateTime.UnixEpoch).TotalSeconds;
|
||||
return new() { IsMet = true, Message = $"窗口内第 {state.Attempts} 次检查通过:{result.Reason}" };
|
||||
}
|
||||
}
|
||||
if (expired)
|
||||
{
|
||||
InvalidateDecision(discardBuffered: false);
|
||||
return new() { IsSkipped = true, Message = $"检查窗口到期,{state.Attempts} 次送检未确认通过,已跳过并继续后续步骤:{state.Reason}" };
|
||||
}
|
||||
if (_pendingDecision is not null) return new() { Message = $"第 {state.Attempts} 次检查中,后续操作持续采集;到期自动继续" };
|
||||
var client = VisionDecisionClient;
|
||||
if (client is null || options.EvidenceMode == VisionEvidenceMode.Sequence && !client.SupportsSequences)
|
||||
{ state.Reason = "检查服务未配置或不支持所需证据"; return new() { Message = state.Reason + ";窗口到期后记录未通过并继续" }; }
|
||||
if (state.Window.Error is { } error) { state.Reason = error; return new() { Message = error }; }
|
||||
if (state.Attempts >= options.MaxChecks) return new() { Message = $"已检查 {state.Attempts} 次仍未通过,窗口结束后继续后续步骤:{state.Reason}" };
|
||||
var quiet = (state.LatestSeconds - state.LastMotionSeconds) * 1000 >= options.CheckSettleMs;
|
||||
var interval = Math.Max(500, options.RetryDelayMs);
|
||||
var sinceRequest = state.Attempts == 0 ? state.ElapsedMs : Environment.TickCount64 - state.LastSubmittedAt;
|
||||
var timeToCheck = state.Attempts == 0 ? quiet || sinceRequest >= interval : sinceRequest >= interval;
|
||||
var frames = state.Window.Frames.Where(f => !_acceptedEvidenceTimes.TryGetValue(_index - 1, out var prior)
|
||||
|| ObservationEvidenceWindow.Time(f) >= prior).ToArray();
|
||||
if (!timeToCheck || state.Window.Version <= state.SentVersion || frames.Length == 0
|
||||
|| options.EvidenceMode == VisionEvidenceMode.Sequence && (frames.Length < 3 || !state.Window.Ready))
|
||||
return new() { Message = $"窗口内观察,优先在手部停稳或离开后检查(已送检 {state.Attempts}/{options.MaxChecks} 次)" };
|
||||
var last = frames[^1];
|
||||
var request = new VisionDecisionRequest(_config.Sop.Name, step.Id, step.Name, step.Description, step.Description,
|
||||
last.FrameId, last.CapturedAt, last.Jpeg, options.EvidenceMode,
|
||||
options.EvidenceMode == VisionEvidenceMode.Sequence ? frames : null, last.SourceSeconds);
|
||||
var remaining = Math.Max(1, options.CheckWindowMs - state.ElapsedMs);
|
||||
var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(Math.Min(options.TimeoutSeconds * 1000d, remaining)));
|
||||
state.Attempts++; state.SentVersion = state.Window.Version; state.LastSubmittedAt = Environment.TickCount64;
|
||||
state.FinishedAt = long.MaxValue;
|
||||
async Task<VisionDecisionResult> CheckAsync()
|
||||
{
|
||||
var decision = await RunDecisionAsync(client, request, cancellation.Token).ConfigureAwait(false);
|
||||
Volatile.Write(ref state.FinishedAt, Environment.TickCount64);
|
||||
return decision;
|
||||
}
|
||||
_pendingDecision = new(CheckAsync(), last.Jpeg, cancellation, request);
|
||||
DecisionCaptured?.Invoke(request); DecisionSubmitted?.Invoke(request);
|
||||
return new() { Message = $"已发送第 {state.Attempts}/{options.MaxChecks} 次检查,后续动作持续采集" };
|
||||
}
|
||||
}
|
||||
@ -51,6 +51,7 @@ public partial class SopEngine
|
||||
public IVisionDecisionClient? VisionDecisionClient { get; set; }
|
||||
/// <summary>包括在途 AI 请求和当前步骤已缓存、尚未送检的证据。</summary>
|
||||
public bool HasPendingDecision => _pendingDecision is not null || _bufferedSteps.ContainsKey(_index)
|
||||
|| _continuousChecks.TryGetValue(_index, out var checking) && checking.Triggered
|
||||
|| VisionDecisionClient is { SupportsSequences: true } && _observationWindows.TryGetValue(_index, out var window)
|
||||
&& window.Window.Error is null && window.Window.HasFreshEvidence;
|
||||
private PendingDecision? _pendingDecision;
|
||||
@ -72,6 +73,10 @@ public partial class SopEngine
|
||||
|
||||
private int _index;
|
||||
private int _roundGeneration;
|
||||
private readonly HashSet<int> _skippedSteps = [];
|
||||
public IReadOnlyCollection<int> SkippedSteps => _skippedSteps;
|
||||
public bool RoundPassed => State == EngineState.Completed && _skippedSteps.Count == 0;
|
||||
public event Action<bool>? RoundFinished;
|
||||
private readonly Dictionary<string, SopRunStatistics> _statistics = new(StringComparer.OrdinalIgnoreCase);
|
||||
public SopRunStatistics Statistics { get; private set; } = new();
|
||||
public SopRunStatistics GetStatistics(string recipeName)
|
||||
@ -157,6 +162,7 @@ public partial class SopEngine
|
||||
|
||||
_index = 0;
|
||||
_nextCaptureIndex = 0;
|
||||
_skippedSteps.Clear();
|
||||
_stepEnteredAt = DateTime.Now;
|
||||
_evaluator.NoteStepEntered(_ordered[0].Id, _stepEnteredAt);
|
||||
|
||||
@ -181,6 +187,7 @@ public partial class SopEngine
|
||||
|
||||
_index = 0;
|
||||
_nextCaptureIndex = 0;
|
||||
_skippedSteps.Clear();
|
||||
_stepEnteredAt = DateTime.Now;
|
||||
if (StepAt(0) is StepDef first) _evaluator.NoteStepEntered(first.Id, _stepEnteredAt);
|
||||
|
||||
@ -230,6 +237,7 @@ public partial class SopEngine
|
||||
|
||||
_observationSequence++;
|
||||
UpdateObservationWindows(frame, captureJpeg, captureDecisionImage);
|
||||
UpdateContinuousChecks(frame, captureJpeg, captureDecisionImage);
|
||||
var step = StepAt(_index);
|
||||
if (step is null) return;
|
||||
|
||||
@ -252,8 +260,9 @@ public partial class SopEngine
|
||||
{
|
||||
StepId = step.Id,
|
||||
Name = step.Name,
|
||||
IsCurrent = true,
|
||||
IsCurrent = !result.IsSkipped && !result.IsMet,
|
||||
IsMet = result.IsMet,
|
||||
IsSkipped = result.IsSkipped,
|
||||
EvidenceJpeg = evidence,
|
||||
Message = result.Message,
|
||||
Elapsed = Statistics.StepElapsed,
|
||||
@ -261,9 +270,16 @@ public partial class SopEngine
|
||||
|
||||
StepSnapshotChanged?.Invoke(snapshot);
|
||||
|
||||
if (!result.IsMet) return;
|
||||
if (!result.IsMet && !result.IsSkipped) return;
|
||||
|
||||
Log("info", $"✓ 步骤 {step.Id}「{step.Name}」完成 — {result.Message}");
|
||||
if (result.IsSkipped)
|
||||
{
|
||||
_skippedSteps.Add(step.Id);
|
||||
ViolationRaised?.Invoke(new() { StepId = step.Id, Type = "check_window_expired", Message = result.Message });
|
||||
Log("viol", $"步骤 {step.Id}「{step.Name}」未通过并跳过 — {result.Message}");
|
||||
}
|
||||
else Log("info", $"✓ 步骤 {step.Id}「{step.Name}」完成 — {result.Message}");
|
||||
_continuousChecks.Remove(_index);
|
||||
|
||||
// 3. 推进
|
||||
_index++;
|
||||
@ -272,10 +288,10 @@ public partial class SopEngine
|
||||
if (_index >= _ordered.Count)
|
||||
{
|
||||
State = EngineState.Completed;
|
||||
Statistics.CompleteRound();
|
||||
Log("info", "★ 全部步骤完成");
|
||||
ClearStepStates();
|
||||
Completed?.Invoke();
|
||||
if (_skippedSteps.Count == 0) Statistics.CompleteRound(); else Statistics.Stop();
|
||||
Log(_skippedSteps.Count == 0 ? "info" : "viol", _skippedSteps.Count == 0 ? "★ 全部步骤完成" : $"本轮结束,{_skippedSteps.Count} 步未通过并跳过");
|
||||
if (_skippedSteps.Count == 0) { ClearStepStates(); Completed?.Invoke(); }
|
||||
RoundFinished?.Invoke(_skippedSteps.Count == 0);
|
||||
|
||||
if (_config.Sop.Settings.AutoResetOnComplete)
|
||||
{
|
||||
@ -361,6 +377,7 @@ public class StepSnapshot
|
||||
|
||||
/// <summary>条件是否已满足</summary>
|
||||
public bool IsMet { get; set; }
|
||||
public bool IsSkipped { get; set; }
|
||||
|
||||
/// <summary>判定说明</summary>
|
||||
public string Message { get; set; } = "";
|
||||
|
||||
@ -6,6 +6,10 @@ namespace SopHelper.Engine.Sop;
|
||||
|
||||
public sealed class AiConfirmation
|
||||
{
|
||||
/// <summary>0 保留原来的等待策略;正值为触发后的检查预算,到期未确认则跳过。</summary>
|
||||
public int CheckWindowMs { get; set; }
|
||||
public int MaxChecks { get; set; } = 3;
|
||||
public int CheckSettleMs { get; set; } = 350;
|
||||
public string EvidenceMode { get; set; } = VisionEvidenceMode.SingleFrame;
|
||||
public int ObservationPreRollMs { get; set; } = 1000;
|
||||
public int ObservationMinMs { get; set; } = 2400;
|
||||
@ -27,6 +31,9 @@ public sealed class AiConfirmation
|
||||
public static class VisionEvidenceMode
|
||||
{
|
||||
public const string SingleFrame = "single_frame", Sequence = "sequence";
|
||||
public static bool IsCheckPolicyValid(AiConfirmation options) => options.CheckWindowMs == 0
|
||||
|| options.CheckWindowMs is >= 500 and <= 60000 && options.MaxChecks is >= 1 and <= 20
|
||||
&& options.CheckSettleMs is >= 100 and <= 3000 && options.CheckSettleMs < options.CheckWindowMs;
|
||||
public static bool IsValid(AiConfirmation options) => options.EvidenceMode == SingleFrame
|
||||
|| options.EvidenceMode == Sequence && options.ObservationPreRollMs is >= 0 and <= 5000
|
||||
&& options.ObservationMinMs is >= 200 and <= 30000 && options.ObservationMaxMs >= options.ObservationMinMs
|
||||
|
||||
82
tests/VisionDecision.Smoke/ContinuousCheckTests.cs
Normal file
82
tests/VisionDecision.Smoke/ContinuousCheckTests.cs
Normal file
@ -0,0 +1,82 @@
|
||||
using System.Collections.Concurrent;
|
||||
using SopHelper.Engine.Common;
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
internal static class ContinuousCheckTests
|
||||
{
|
||||
private static void Check(bool condition, string reason) { if (!condition) throw new Exception(reason); }
|
||||
private static async Task Until(Func<bool> condition)
|
||||
{
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
while (!condition() && watch.Elapsed.TotalSeconds < 3) await Task.Delay(5);
|
||||
Check(condition(), "异步限时检查没有推进");
|
||||
}
|
||||
private sealed class Client : IVisionDecisionClient
|
||||
{
|
||||
public ConcurrentQueue<(VisionDecisionRequest Request, TaskCompletionSource<VisionDecisionResult> Result)> Calls = new();
|
||||
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken token)
|
||||
{
|
||||
var result = new TaskCompletionSource<VisionDecisionResult>(); Calls.Enqueue((request, result)); return result.Task;
|
||||
}
|
||||
}
|
||||
private static SopConfig Config(int steps = 2)
|
||||
{
|
||||
var config = new SopConfig(); config.Sop.Settings.AutoResetOnComplete = false;
|
||||
for (var i = 0; i < steps; i++)
|
||||
{
|
||||
config.Sop.Regions["r" + i] = new() { X1 = i * 100, Y1 = 0, X2 = i * 100 + 90, Y2 = 100 };
|
||||
config.Sop.Steps.Add(new() { Id = i + 1, Name = "工序" + i, Description = "结果到位",
|
||||
Detection = new() { Method = ConditionMethod.HandInRegion, Region = "r" + i, Hand = "right", StableFrames = 1 },
|
||||
AiConfirmation = new() { CheckWindowMs = 2000, MaxChecks = 2, CheckSettleMs = 150,
|
||||
RetryDelayMs = 500, ObservationSampleMs = 100 } });
|
||||
}
|
||||
return config;
|
||||
}
|
||||
private static FrameResult Frame(int id, double seconds, int x) => new() { FrameId = id, SourceSeconds = seconds,
|
||||
Timestamp = DateTime.UnixEpoch.AddSeconds(seconds), Size = (200, 100),
|
||||
Hands = [new() { HandType = HandType.Right, Rect = new(x, 20, 10, 10) }] };
|
||||
public static async Task RunAsync()
|
||||
{
|
||||
var client = new Client(); var engine = new SopEngine { VisionDecisionClient = client }; engine.Load(Config()); engine.Start();
|
||||
var snapshots = new List<StepSnapshot>(); int evaluated = 0, alarms = 0; bool? passed = null;
|
||||
engine.StepSnapshotChanged += snapshots.Add; engine.DecisionEvaluated += (_, _, _) => evaluated++;
|
||||
engine.ViolationRaised += _ => alarms++; engine.RoundFinished += result => passed = result;
|
||||
void Feed(int id, double seconds, int x) => engine.ProcessFrame(Frame(id, seconds, x), () => [(byte)id]);
|
||||
Feed(1, 0, 10); Feed(2, .1, 30);
|
||||
Check(client.Calls.Count == 0, "进入后仍在移动不能立即检查");
|
||||
Feed(3, .3, 30); await Until(() => client.Calls.Count == 1);
|
||||
var first = client.Calls.ElementAt(0);
|
||||
Check(first.Request.FrameId == 3, "停稳后须使用当时的新画面,不能送刚进入的旧画面");
|
||||
Feed(4, .4, 120); Feed(5, .6, 120); // 人继续做第二步,第一步 AI 仍在途。
|
||||
first.Result.SetResult(new(false, .9, "未完成"));
|
||||
await Until(() => { engine.ProcessFrame(Frame(5, .6, 120)); return evaluated == 1; });
|
||||
await Until(() => { engine.ProcessFrame(Frame(5, .6, 120)); return client.Calls.Count == 2; });
|
||||
var retry = client.Calls.ElementAt(1);
|
||||
Check(retry.Request.StepId == 1 && retry.Request.FrameId > first.Request.FrameId, "窗口内重试应使用新证据");
|
||||
retry.Result.SetResult(new(false, .9, "仍未完成"));
|
||||
await Until(() => { engine.ProcessFrame(Frame(5, .6, 120)); return evaluated == 2; });
|
||||
Feed(6, 2.1, 120);
|
||||
Check(engine.CurrentStep?.Id == 2 && snapshots.Any(s => s.StepId == 1 && s.IsSkipped && !s.IsMet)
|
||||
&& alarms == 1, "限时多次未通过必须标记跳过、告警并继续下一步");
|
||||
engine.ProcessFrame(Frame(6, 2.1, 120)); await Until(() => client.Calls.Count == 3);
|
||||
var next = client.Calls.ElementAt(2);
|
||||
Check(next.Request.StepId == 2 && next.Request.FrameId is 5 or 6, "下一步须保留第一步等待期间取得的连续动作证据");
|
||||
next.Result.SetResult(new(true, .99, "第二步结果可见"));
|
||||
await Until(() => { engine.ProcessFrame(Frame(6, 2.1, 120)); return engine.State == EngineState.Completed; });
|
||||
Check(passed == false && !engine.RoundPassed && engine.Statistics.CompletedCount == 0 && engine.SkippedSteps.Contains(1),
|
||||
"跳过不能算合格完成或增加合格产量");
|
||||
engine.Reset(); Check(engine.SkippedSteps.Count == 0 && !engine.HasPendingDecision, "复位必须清空跳过状态和所有窗口");
|
||||
|
||||
// 服务永不返回:窗口硬截止取消本步;迟到的 true 不得影响下一步。
|
||||
var slow = new Client(); var timed = new SopEngine { VisionDecisionClient = slow }; timed.Load(Config()); timed.Start();
|
||||
void SlowFeed(int id, double seconds, int x) => timed.ProcessFrame(Frame(id, seconds, x), () => [(byte)id]);
|
||||
SlowFeed(1, 0, 10); SlowFeed(2, .2, 10); await Until(() => slow.Calls.Count == 1);
|
||||
SlowFeed(3, .4, 120); SlowFeed(4, .6, 120); SlowFeed(5, 2.1, 120);
|
||||
Check(timed.CurrentStep?.Id == 2 && timed.SkippedSteps.Contains(1), "服务挂起也不能阻塞到检查窗口之外");
|
||||
slow.Calls.ElementAt(0).Result.SetResult(new(true, 1, "迟到结果"));
|
||||
timed.ProcessFrame(Frame(5, 2.1, 120)); await Until(() => slow.Calls.Count == 2);
|
||||
Check(timed.CurrentStep?.Id == 2 && timed.SkippedSteps.Contains(1), "已跳过步骤的迟到结果不能放行后续步骤");
|
||||
timed.Stop(); Check(!timed.HasPendingDecision, "停止必须取消限时检查和未来步骤缓存");
|
||||
Console.WriteLine("PASS: 停稳触发、新帧重试、限时跳过、后续动作持续取证、挂起硬截止、迟到结果隔离和非合格整轮统计");
|
||||
}
|
||||
}
|
||||
@ -150,6 +150,7 @@ await LayaChecks.RunAsync(args);
|
||||
await D3Checks.RunAsync(args);
|
||||
await BufferedEvidenceChecks.RunAsync();
|
||||
await ObservationWindowChecks.RunAsync();
|
||||
await ContinuousCheckTests.RunAsync();
|
||||
HandContactChecks.Run();
|
||||
await TriggerImageChecks.RunAsync();
|
||||
await DynamicRegionChecks.RunAsync();
|
||||
|
||||
Loading…
Reference in New Issue
Block a user