143 lines
8.5 KiB
C#
143 lines
8.5 KiB
C#
using Avalonia;
|
|
using Avalonia.Controls;
|
|
using Avalonia.Headless;
|
|
using Avalonia.Markup.Xaml.Styling;
|
|
using Avalonia.Themes.Fluent;
|
|
using Avalonia.Threading;
|
|
using Avalonia.VisualTree;
|
|
using OpenCvSharp;
|
|
using Prism.Dialogs;
|
|
using SopHelper.Engine.Common;
|
|
using SopHelper.Engine.Sop;
|
|
using SopHelper.Engine.Training;
|
|
using SopHelper.Training;
|
|
using SopHelper.VVMs.RecipeEditor;
|
|
using Window = Avalonia.Controls.Window;
|
|
|
|
internal static class Program
|
|
{
|
|
[STAThread]
|
|
public static void Main()
|
|
{
|
|
var root = Path.Combine(Path.GetTempPath(), "video-flow-test-" + Guid.NewGuid().ToString("N"));
|
|
var previousRoot = Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
|
|
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", root);
|
|
try
|
|
{
|
|
AppBuilder.Configure<Application>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
|
|
Application.Current!.Styles.Add(new FluentTheme());
|
|
Application.Current.Styles.Add(new StyleInclude(new Uri("avares://SopHelper.Avalonia/")) { Source = new Uri("avares://SopHelper.Avalonia/Themes/Styles.axaml") });
|
|
CheckAiFlow();
|
|
CheckVideoPage(root);
|
|
}
|
|
finally
|
|
{
|
|
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", previousRoot);
|
|
if (Directory.Exists(root)) Directory.Delete(root, true);
|
|
}
|
|
}
|
|
|
|
private static void CheckAiFlow()
|
|
{
|
|
var config = SopConfigLoader.Parse("""
|
|
sop:
|
|
name: 流程测试
|
|
settings: { auto_reset_on_complete: true }
|
|
regions: { work: { x1: 0, y1: 0, x2: 64, y2: 48 } }
|
|
steps:
|
|
- id: 1
|
|
name: 装配
|
|
description: 零件安装到位
|
|
detection: { method: hand_in_region, region: work, stable_frames: 1, tolerance: 1 }
|
|
ai_confirmation: { image_mode: fixed_region, image_region: work, timeout_seconds: 2 }
|
|
""");
|
|
var fake = new FakeDecision();
|
|
using var test = new SopVideoFlowTest(config, fake);
|
|
test.Start();
|
|
using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 60, 90));
|
|
var frame = new FrameResult { FrameId = 12, Timestamp = DateTime.Now, Size = (64, 48), Hands = [new Hand { Rect = new(20, 20, 10, 10) }] };
|
|
test.ProcessResult(frame, image);
|
|
Until(() => fake.Request is not null);
|
|
Check(!test.IsCompleted && fake.Request!.FrameId == 12 && fake.Request.Jpeg.Length > 0, "Hand trigger submits the exact video frame to AI without completing early");
|
|
var drain = test.FinishPendingDecisionAsync();
|
|
Check(!drain.IsCompleted, "End of video waits for the outstanding AI decision");
|
|
fake.Result.SetResult(new(true, .99, "已安装"));
|
|
Pump(drain);
|
|
Check(test.IsCompleted && test.Finish("播放结束").Contains("检测通过") && test.Details.Contains("✓ 1 装配"), "Final AI confirmation completes the flow and preserves the completed step result");
|
|
Check(config.Sop.Settings.AutoResetOnComplete, "Test run preserves the editor configuration");
|
|
using var cancelled = new SopVideoFlowTest(config, new FakeDecision());
|
|
cancelled.Start();
|
|
cancelled.ProcessResult(frame, image);
|
|
var cancelledDrain = cancelled.FinishPendingDecisionAsync();
|
|
cancelled.Dispose(); Pump(cancelledDrain);
|
|
Check(!cancelled.IsCompleted, "Stopping a test cancels pending AI without reporting success");
|
|
}
|
|
|
|
private static void CheckVideoPage(string root)
|
|
{
|
|
var store = new RecipeWorkspace(root);
|
|
var config = new SopConfig(); config.Sop.Name = "视频测试界面"; config.Sop.Parts = [];
|
|
var vm = new RecipeEditorViewModel();
|
|
vm.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "config", config }, { "new", true } });
|
|
vm.SaveCommand.Execute();
|
|
var model = vm.SopRecording!;
|
|
Check(!model.TestFlowCommand.CanExecute(), "Test flow is disabled without a saved standard video");
|
|
Directory.CreateDirectory(Path.GetDirectoryName(model.StandardVideoPath)!);
|
|
using (var writer = new VideoWriter(model.StandardVideoPath, FourCC.MJPG, 10, new OpenCvSharp.Size(64, 48)))
|
|
{
|
|
Check(writer.IsOpened(), "Standard test video opens");
|
|
for (var i = 0; i < 10; i++)
|
|
{
|
|
using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 60, 90)); writer.Write(image);
|
|
}
|
|
}
|
|
// Unsupported condition exercises playback and incomplete results without hardware/models/API.
|
|
config.Sop.Steps = [new StepDef { Id = 1, Name = "待配置步骤", Description = "验证当前编辑配置", Detection = new() { Method = "unsupported" } }];
|
|
model.FlowTestConfigProvider = () => config;
|
|
var view = new RecipeEditor { DataContext = vm };
|
|
var window = new Window { Content = view, Width = 1040, Height = 760 }; window.Show(); window.UpdateLayout();
|
|
var tabs = view.GetVisualDescendants().OfType<TabControl>().Single();
|
|
tabs.SelectedItem = tabs.Items.OfType<TabItem>().Single(t => t.Header?.ToString() == "SOP流程视频");
|
|
window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
|
|
var button = view.GetVisualDescendants().OfType<Button>().Single(b => ReferenceEquals(b.Command, model.TestFlowCommand));
|
|
Check(button.Content?.ToString() == "测试流程" && button.IsEffectivelyVisible && model.TestFlowCommand.CanExecute(), "SOP video page exposes the enabled test flow button");
|
|
model.TestFlowCommand.Execute(); Until(() => !model.IsBusy);
|
|
Check(model.IsTestingFlow && model.Playback.IsPlaying && model.DisplayImage is { PixelWidth: 64, PixelHeight: 48 }, "Test button plays and displays the standard video without a camera");
|
|
Check(!model.TestFlowCommand.CanExecute() && !model.PlayVideoCommand.CanExecute() && !model.PreviewCommand.CanExecute() && !model.CanSeekVideo, "Test run prevents restart, playback switching, camera switching, and seeking");
|
|
Check(!view.FindControl<Slider>("VideoSeekSlider")!.IsEnabled, "Actual seek slider is disabled during flow testing");
|
|
Until(() => !model.IsTestingFlow);
|
|
Check(model.Playback.IsAtEnd && model.FlowTestStatus.Contains("流程未完成") && model.FlowTestDetails.Contains("待配置步骤"), "Video EOF reports incomplete flow and shows the step reason");
|
|
model.TestFlowCommand.Execute(); Until(() => !model.IsBusy);
|
|
Check(model.Playback.Progress < 50, "Each test restarts the video from its beginning");
|
|
model.StopVideoCommand.Execute(); Until(() => !model.IsBusy);
|
|
Check(!model.IsTestingFlow && !model.Playback.IsLoaded && model.FlowTestStatus.Contains("测试已停止"), "Stop playback also stops detection and preserves the test summary");
|
|
model.TestFlowCommand.Execute(); Until(() => !model.IsBusy);
|
|
Pump(vm.ShutdownAsync());
|
|
Check(!model.IsTestingFlow && !model.Playback.IsLoaded && model.Playback.FrameProcessor is null, "Closing the editor releases playback and flow detection");
|
|
using (var exclusive = new FileStream(model.StandardVideoPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
|
Check(exclusive.Length > 0, "Closing flow test unlocks the video file");
|
|
window.Close(); vm.OnDialogClosed();
|
|
}
|
|
|
|
private static void Until(Func<bool> ready)
|
|
{
|
|
var watch = System.Diagnostics.Stopwatch.StartNew();
|
|
while (!ready() && watch.Elapsed < TimeSpan.FromSeconds(10))
|
|
{
|
|
using var cancellation = new CancellationTokenSource(10);
|
|
Dispatcher.UIThread.MainLoop(cancellation.Token);
|
|
}
|
|
if (!ready()) throw new TimeoutException("Smoke test timed out");
|
|
Dispatcher.UIThread.RunJobs();
|
|
}
|
|
private static void Pump(Task task) { Until(() => task.IsCompleted); task.GetAwaiter().GetResult(); }
|
|
private static void Check(bool value, string message) { if (!value) throw new Exception(message); Console.WriteLine("PASS: " + message); }
|
|
private sealed class FakeDecision : IVisionDecisionClient
|
|
{
|
|
public VisionDecisionRequest? Request;
|
|
public TaskCompletionSource<VisionDecisionResult> Result { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
|
|
{ Request = request; return Result.Task.WaitAsync(cancellationToken); }
|
|
}
|
|
}
|