aisop/tests/VisionDecision.Smoke/BufferedEvidenceChecks.cs

196 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Concurrent;
using SopHelper.Engine.Common;
using SopHelper.Engine.Sop;
internal static class BufferedEvidenceChecks
{
public static async Task RunAsync()
{
await ContinuousSteps();
await RejectionDoesNotSkip();
await RepeatedEntryNeedsNewAction();
await LeaveAndMoveEvidence();
await LifecycleInvalidatesQueue();
Console.WriteLine("PASS: 连续操作跨多步缓存、原始帧与裁剪、按序AI确认、拒绝不跳步、同区重新进入、离开/移动轨迹、暂停复位停止清空缓存");
}
private static SopConfig Config(int count = 3)
{
var config = new SopConfig(); config.Sop.Name = "连续操作";
config.Sop.Settings.AutoResetOnComplete = false;
for (var i = 0; i < count; i++)
{
var key = "r" + i;
config.Sop.Regions[key] = new() { X1 = i * 60, Y1 = 0, X2 = i * 60 + 50, Y2 = 50 };
config.Sop.Steps.Add(new() { Id = i + 1, Name = "操作" + (i + 1), Description = "区域内可见本步结果",
Detection = new() { Method = ConditionMethod.HandInRegion, Region = key, Hand = "right", StableFrames = 1, Tolerance = 1 },
AiConfirmation = new() { ImageMode = VisionImageMode.FixedRegion, ImageRegion = key, RetryDelayMs = 0, TimeoutSeconds = 5 } });
}
return config;
}
private static FrameResult Frame(long id, int? region) => new()
{
FrameId = id, Timestamp = new DateTime(2026, 11, 18).AddMilliseconds(id * 100), Size = (240, 80),
Hands = region is { } i ? [new Hand { HandType = HandType.Right, Rect = new(i * 60 + 10, 10, 10, 10) }] : []
};
private static SopEngine Engine(SopConfig config, DelayedClient client)
{
var engine = new SopEngine { VisionDecisionClient = client }; engine.Load(config); engine.Start(); return engine;
}
private static async Task Until(Func<bool> ready)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
while (!ready() && watch.Elapsed < TimeSpan.FromSeconds(3)) await Task.Delay(5);
Check(ready(), "异步判定未按预期完成");
}
private static void Check(bool value, string message) { if (!value) throw new Exception(message); }
private static async Task ContinuousSteps()
{
var client = new DelayedClient(); var engine = Engine(Config(), client);
var captured = new List<(long Frame, int Region, byte[] Jpeg)>();
var completed = new List<(int Step, byte[]? Jpeg)>();
engine.StepSnapshotChanged += s => { if (s.IsMet) completed.Add((s.StepId, s.EvidenceJpeg)); };
for (var i = 0; i < 3; i++)
{
var frame = Frame(61 + i, i);
engine.ProcessFrame(frame, captureDecisionImage: region =>
{
var jpeg = new byte[] { (byte)frame.FrameId, (byte)region!.X1 };
captured.Add((frame.FrameId, region.X1, jpeg)); return jpeg;
});
}
await Until(() => client.Calls.Count == 1);
Check(captured.Count == 3 && completed.Count == 0 && engine.CurrentStep!.Id == 1,
"第一步AI尚未返回时,后面两步必须完成独立取图且不能提前放行");
for (var i = 0; i < 3; i++)
{
await Until(() => client.Calls.Count == i + 1);
var call = client.Calls.ElementAt(i);
Check(call.Request.StepId == i + 1 && call.Request.FrameId == 61 + i
&& call.Request.CapturedAt == Frame(61 + i, i).Timestamp
&& captured[i].Region == i * 60 && ReferenceEquals(call.Request.Jpeg, captured[i].Jpeg),
"后续AI必须使用该步骤操作发生时的原帧、时间和裁剪,不能换成当前结束画面");
call.Result.SetResult(new(true, .99, "已完成"));
await Until(() => call.Result.Task.IsCompleted);
// EOF 之后只轮询缓存和判定,不再提供相机画面。
await Until(() => { engine.ProcessFrame(Frame(999, null)); return completed.Count == i + 1; });
if (i < 2) engine.ProcessFrame(Frame(999, null));
}
Check(engine.State == EngineState.Completed && engine.Statistics.CompletedCount == 1
&& completed.Select(s => s.Step).SequenceEqual(new[] { 1, 2, 3 })
&& captured.Count == 3 && !engine.HasPendingDecision,
"连续三步必须按序确认、保留各自证据且只计一轮,不得要求重做动作");
engine.Stop();
}
private static async Task RejectionDoesNotSkip()
{
var client = new DelayedClient(); var engine = Engine(Config(2), client);
engine.ProcessFrame(Frame(1, 0), captureDecisionImage: _ => [1]);
engine.ProcessFrame(Frame(2, 1), captureDecisionImage: _ => [2]);
await Until(() => client.Calls.Count == 1);
client.Calls.First().Result.SetResult(new(false, .99, "第一步不合格"));
await Until(() => { engine.ProcessFrame(Frame(3, null)); return !engine.HasPendingDecision; });
Check(engine.CurrentStep!.Id == 1 && client.Calls.Count == 1, "第一步被拒绝时不能用后续动作或缓存跳过失败步骤");
await Task.Delay(550);
engine.ProcessFrame(Frame(4, 0), captureDecisionImage: _ => [4]);
await Until(() => client.Calls.Count == 2);
client.Calls.Last().Result.SetResult(new(true, .99, "返工合格"));
await Until(() => { engine.ProcessFrame(Frame(5, null)); return engine.CurrentStep?.Id == 2; });
engine.ProcessFrame(Frame(6, null));
await Until(() => client.Calls.Count == 3);
Check(client.Calls.Last().Request is { StepId: 2, FrameId: 2 }, "前序返工确认后仍应保留后续原始动作证据");
engine.Stop();
}
private static async Task RepeatedEntryNeedsNewAction()
{
foreach (var confirmEarly in new[] { false, true })
{
var config = Config(2); config.Sop.Steps[1].Detection!.Region = "r0";
var client = new DelayedClient(); var engine = Engine(config, client);
var captured = 0;
byte[] Capture() { captured++; return [(byte)captured]; }
for (var i = 1; i <= 4; i++) engine.ProcessFrame(Frame(i, 0), captureDecisionImage: _ => Capture());
Check(captured == 1, "手在同一区域停留不能提前缓存后续同区进入步骤");
await Until(() => client.Calls.Count == 1);
if (confirmEarly)
{
client.Calls.First().Result.SetResult(new(true, .99, "已完成"));
await Until(() => { engine.ProcessFrame(Frame(4, 0), captureDecisionImage: _ => Capture()); return engine.CurrentStep?.Id == 2; });
engine.ProcessFrame(Frame(4, 0), captureDecisionImage: _ => Capture());
Check(captured == 1, "前序AI提前确认后仍不能用同一次停留直接触发下一步");
}
engine.ProcessFrame(Frame(5, null), captureDecisionImage: _ => Capture());
engine.ProcessFrame(Frame(6, 0), captureDecisionImage: _ => Capture());
Check(captured == 2, "重新离开并进入后必须捕获下一次操作,不能等待前序AI");
engine.Stop();
}
}
private static async Task LeaveAndMoveEvidence()
{
foreach (var method in new[] { ConditionMethod.HandLeaveRegion, ConditionMethod.HandMove })
{
var config = Config(2); var condition = config.Sop.Steps[1].Detection!;
condition.Method = method;
if (method == ConditionMethod.HandMove)
{
condition.FromRegion = "r1"; condition.ToRegion = "r2";
config.Sop.Regions["r2"] = new() { X1 = 120, Y1 = 0, X2 = 170, Y2 = 50 };
}
else config.Sop.Steps[1].AiConfirmation = new() { ImageMode = VisionImageMode.Hand, HandPadding = 5, HandMinSize = 32 };
var client = new DelayedClient(); var engine = Engine(config, client);
engine.ProcessFrame(Frame(10, 0), captureDecisionImage: _ => [10]);
var frame = Frame(11, 1);
engine.ProcessFrame(frame, captureDecisionImage: _ => [11]);
var count = 0;
frame = Frame(12, method == ConditionMethod.HandMove ? 2 : null);
engine.ProcessFrame(frame, captureDecisionImage: region =>
{
if (method == ConditionMethod.HandLeaveRegion) Check(region is { X1: > 50, X2: < 100 }, "后续离开步骤必须使用自己的离开前手部位置裁剪离开后的新帧");
count++; return [12];
});
Check(count == 1, "前序AI未返回时不能漏掉后续手离开或跨区域移动");
await Until(() => client.Calls.Count == 1);
client.Calls.First().Result.SetResult(new(true, .99, "完成"));
await Until(() => { engine.ProcessFrame(Frame(100, null)); return engine.CurrentStep?.Id == 2; });
engine.ProcessFrame(Frame(101, null));
await Until(() => client.Calls.Count == 2);
Check(client.Calls.Last().Request.FrameId == 12, "轨迹步骤在手已离开后仍应提交当时取得的画面");
engine.Stop();
}
}
private static async Task LifecycleInvalidatesQueue()
{
foreach (var action in new Action<SopEngine>[] { e => e.Reset(), e => { e.TogglePause(); e.TogglePause(); }, e => { e.Stop(); e.Start(); } })
{
var client = new DelayedClient(); var engine = Engine(Config(2), client);
engine.ProcessFrame(Frame(1, 0), captureDecisionImage: _ => [1]); engine.ProcessFrame(Frame(2, 1), captureDecisionImage: _ => [2]);
await Until(() => client.Calls.Count == 1);
action(engine);
client.Calls.First().Result.SetResult(new(true, .99, "旧轮次结果"));
await Task.Delay(20); engine.ProcessFrame(Frame(100, null));
Check(engine.CurrentStep?.Id == 1 && !engine.HasPendingDecision && client.Calls.Count == 1,
"暂停、复位、停止必须同时失效在途请求和全部后续缓存,不能跨轮次放行");
engine.Stop();
}
}
private sealed class DelayedClient : IVisionDecisionClient
{
public ConcurrentQueue<Call> Calls { get; } = new();
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
{
var call = new Call(request); Calls.Enqueue(call); return call.Result.Task.WaitAsync(cancellationToken);
}
}
private sealed class Call(VisionDecisionRequest request)
{
public VisionDecisionRequest Request { get; } = request;
public TaskCompletionSource<VisionDecisionResult> Result { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
}