2070 lines
157 KiB
C#
2070 lines
157 KiB
C#
using Avalonia;
|
||
using Avalonia.Controls;
|
||
using Avalonia.Controls.ApplicationLifetimes;
|
||
using Avalonia.Headless;
|
||
using Avalonia.Media.Imaging;
|
||
using Avalonia.Media;
|
||
using Avalonia.Threading;
|
||
using Prism.Ioc;
|
||
using Prism.Dialogs;
|
||
using SopHelper;
|
||
using SopHelper.Engine.Camera;
|
||
using SopHelper.Engine.Recipes;
|
||
using SopHelper.Models;
|
||
using SopHelper.SopVideo;
|
||
using SopHelper.VVMs.SopPage;
|
||
using SopHelper.VVMs.RecipeEditor;
|
||
using System.Text.Json;
|
||
using Avalonia.VisualTree;
|
||
using OpenCvSharp;
|
||
using SopHelper.Engine.SopAgent;
|
||
using SopHelper.Engine.Sop;
|
||
using Window = Avalonia.Controls.Window;
|
||
using Point = Avalonia.Point;
|
||
using Size = Avalonia.Size;
|
||
using Avalonia.Input;
|
||
|
||
internal static class Smoke
|
||
{
|
||
private static int _exit=1;
|
||
private static bool _visionOnly;
|
||
private static bool _processImagesOnly;
|
||
private static bool _recipeSelectionOnly;
|
||
private static string? _agentSettingsFile;
|
||
private static readonly FakeCamera Camera=new();
|
||
private static readonly LicenseUiTests Licensing = new();
|
||
[STAThread]
|
||
public static int Main(string[] args)
|
||
{
|
||
if (args.Contains("--add-step-only"))
|
||
{
|
||
CheckAddStep();
|
||
return 0;
|
||
}
|
||
|
||
_visionOnly=args.Contains("--vision-only");
|
||
if (args.Contains("--license-ui-only")) Licensing.Expire();
|
||
_processImagesOnly=args.Contains("--process-images-only");
|
||
_recipeSelectionOnly=args.Contains("--recipe-selection-only");
|
||
var agentSettingsIndex=Array.IndexOf(args,"--agent-settings-file");
|
||
if(agentSettingsIndex>=0)
|
||
{
|
||
if(agentSettingsIndex+1>=args.Length)throw new ArgumentException("--agent-settings-file 后需提供设置文件路径");
|
||
_agentSettingsFile=Path.GetFullPath(args[agentSettingsIndex+1]);
|
||
}
|
||
var previousRoot=Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
|
||
var dataRoot=Path.Combine(Path.GetTempPath(),"sophelper-layout-smoke-"+Guid.NewGuid().ToString("N"));
|
||
Directory.CreateDirectory(dataRoot);
|
||
if(_agentSettingsFile is not null)
|
||
{
|
||
Directory.CreateDirectory(Path.Combine(dataRoot,"workspace"));
|
||
File.Copy(_agentSettingsFile,Path.Combine(dataRoot,"workspace","sop-agent.json"));
|
||
}
|
||
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT",dataRoot);
|
||
var settingsPath=Path.Combine(dataRoot,"workspace","settings.json");
|
||
var settingsBefore=File.Exists(settingsPath)?File.ReadAllBytes(settingsPath):null;
|
||
System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());
|
||
Environment.SetEnvironmentVariable("SOPHELPER_CPU_THREADS","4");
|
||
try
|
||
{
|
||
if (args.Contains("--auto-login-only")) PrepareAutoLogin(dataRoot);
|
||
AppBuilder.Configure(()=>new App(Camera, Licensing.Service)).UseSkia()
|
||
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing=false })
|
||
.LogToTrace(Avalonia.Logging.LogEventLevel.Warning)
|
||
.AfterSetup(_=>
|
||
{
|
||
var lifetime=(IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!;
|
||
lifetime.Startup+=(_,_)=>Dispatcher.UIThread.Post(async()=>await Run(lifetime));
|
||
}).StartWithClassicDesktopLifetime([],ShutdownMode.OnExplicitShutdown);
|
||
if(args.Contains("--camera-lifecycle-only")&&_exit==0)
|
||
Check(!Camera.IsConnected&&Camera.DisposeCount>0,"Application exit releases the retained camera connection");
|
||
}
|
||
finally
|
||
{
|
||
if(settingsBefore is not null)File.WriteAllBytes(settingsPath,settingsBefore);
|
||
else if(File.Exists(settingsPath))File.Delete(settingsPath);
|
||
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT",previousRoot);
|
||
if(!Path.GetFullPath(dataRoot).StartsWith(Path.GetFullPath(Path.GetTempPath())))throw new Exception("Unexpected test data root");
|
||
Directory.Delete(dataRoot,true);
|
||
}
|
||
return _exit;
|
||
}
|
||
private static async Task Run(IClassicDesktopStyleApplicationLifetime lifetime)
|
||
{
|
||
try
|
||
{
|
||
var userCameraPath=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"SopHelper","last-camera.json");
|
||
var userCameraBefore=File.Exists(userCameraPath)?File.ReadAllBytes(userCameraPath):null;
|
||
await Task.Delay(150);
|
||
var app=(App)Application.Current!;var window=lifetime.MainWindow!;
|
||
if (Environment.GetCommandLineArgs().Contains("--license-ui-only"))
|
||
{ await Licensing.Run(app, lifetime); _exit = 0; return; }
|
||
if (Environment.GetCommandLineArgs().Contains("--login-users-only"))
|
||
{ await CheckLoginUserSelection(window); _exit = 0; return; }
|
||
if (Environment.GetCommandLineArgs().Contains("--auto-login-only"))
|
||
{ await CheckAutoLogin(app); _exit = 0; return; }
|
||
if (Environment.GetCommandLineArgs().Contains("--permissions-only"))
|
||
{ await CheckPermissions(app, window); await CheckOwnPasswords(window); _exit = 0; return; }
|
||
// 既有业务回归使用显式测试管理员;不改变生产环境默认未登录状态。
|
||
UserAccess.Current.Setup("smoke-admin", "SmokePassword123");
|
||
if (Environment.GetCommandLineArgs().Contains("--recipe-transfer-only"))
|
||
{
|
||
// 单独跑配方导入导出入口检查:视图需要真实窗口宿主,确认窗才能以模态方式打开。
|
||
var transferModel = app.Container.Resolve<SopPageViewModel>();
|
||
var transferView = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(transferModel);
|
||
var transferWindow = new Window { Content = transferView, Width = 900, Height = 900 };
|
||
transferWindow.Show(); await Task.Delay(120);
|
||
await CheckRecipeTransfer(lifetime, transferView, transferModel);
|
||
transferWindow.Close(); _exit = 0; return;
|
||
}
|
||
if(Environment.GetCommandLineArgs().Contains("--djev-shutdown-only"))
|
||
{
|
||
// 注入尚未完成的启动任务,验证关闭必须先取消并等待,且重复点击不会提前销毁窗口。
|
||
var startup=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
var fields=System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.NonPublic;
|
||
var options=new D3StartupOptions(new("http://127.0.0.1:8766/v1/systemone"),
|
||
Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!,"unused","unused","unused",
|
||
TimeSpan.FromSeconds(2),TimeSpan.FromMilliseconds(20));
|
||
// 用当前进程的错误启动时间模拟过期记录,不接触真实模型,也不能结束测试宿主。
|
||
File.WriteAllText(options.MarkerPath,JsonSerializer.Serialize(new D3ProcessMarker(Environment.ProcessId,DateTime.UnixEpoch)));
|
||
typeof(App).GetField("_d3Options",fields)!.SetValue(app,options);
|
||
typeof(App).GetField("_d3Startup",fields)!.SetValue(app,startup.Task);
|
||
var cancellation=(CancellationTokenSource)typeof(App).GetField("_d3StartupCancellation",fields)!.GetValue(app)!;
|
||
window.Close();window.Close();
|
||
Check(cancellation.IsCancellationRequested&&window.IsVisible&&Camera.DisposeCount==0,"退出先取消模型启动,等待期间重复关闭不提前释放资源");
|
||
startup.SetResult();
|
||
for(var retry=0;window.IsVisible&&retry<100;retry++)await Task.Delay(20);
|
||
Check(!window.IsVisible&&!File.Exists(options.MarkerPath)&&Camera.DisposeCount>0,"启动任务完成后清理模型记录、关闭窗口并释放相机");
|
||
_exit=0;return;
|
||
}
|
||
if(Environment.GetCommandLineArgs().Contains("--check-progress-only"))
|
||
{ await CheckRemainingWindowProgress(app,window);_exit=0;return; }
|
||
if(Environment.GetCommandLineArgs().Contains("--standard-sop-only"))
|
||
{ await CheckStandardSopPlayback(app,window);_exit=0;return; }
|
||
if(Environment.GetCommandLineArgs().Contains("--step-counts-only"))
|
||
{ await CheckStepCounts(app,window);_exit=0;return; }
|
||
if(Environment.GetCommandLineArgs().Contains("--startup-recipe-only"))
|
||
{
|
||
var model=app.Container.Resolve<SopPageViewModel>();
|
||
Check(model.SelectedRecipe is not null&&model.ActiveRecipe==model.SelectedRecipe&&model.StepCards.Count>0,
|
||
"Startup applies the selected recipe and populates step cards");
|
||
Check(!model.IsRunning&&!Camera.IsConnected&&!Camera.IsGrabbing&&Camera.ConnectCount==0,
|
||
"Startup application never connects or starts the camera");
|
||
CheckRecipePreferences(app);
|
||
_exit=0;return;
|
||
}
|
||
if(Environment.GetCommandLineArgs().Contains("--time-display-only"))
|
||
{
|
||
foreach(var (duration,expected) in new[]{(TimeSpan.Zero,"00:00:00"),(TimeSpan.FromMilliseconds(999),"00:00:00"),
|
||
(TimeSpan.FromMilliseconds(1999),"00:00:01"),(TimeSpan.FromMilliseconds(60001),"00:01:00"),
|
||
(TimeSpan.FromHours(25)+TimeSpan.FromMilliseconds(1250),"25:00:01")})
|
||
Check(SopPageViewModel.FormatDuration(duration)==expected,"Elapsed time drops fractional seconds: "+duration);
|
||
var model=app.Container.Resolve<SopPageViewModel>();
|
||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||
var name=Path.GetFileNameWithoutExtension(model.SelectedRecipe)!;
|
||
SopStandardVideoDuration.Remember(new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!).DirectoryFor(name),TimeSpan.FromSeconds(3.25));
|
||
var statistics=engine.GetStatistics(name);statistics.StartRound();await Task.Delay(1150);statistics.Pause();await Task.Delay(120);
|
||
Check(model.FlowElapsedText=="00:00:01"&&model.StepElapsedText=="00:00:01"
|
||
&&model.StandardDurationText=="00:00:03"&&model.AverageDurationText=="00:00:00","Main statistics render whole seconds");
|
||
Check(new StepCard().ElapsedText=="00:00:00","New step cards start with whole seconds");
|
||
model.StepCards.Clear();model.StepCards.Add(new(){StepId=1,Name="计时步骤",SaveCompletionImage=false});
|
||
typeof(SopPageViewModel).GetMethod("UpdateCard",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!
|
||
.Invoke(model,[new SopHelper.Engine.Sop.StepSnapshot{StepId=1,Elapsed=TimeSpan.FromMilliseconds(1999)}]);
|
||
Check(model.StepCards[0].ElapsedText=="00:00:01","Step snapshots render whole seconds");
|
||
model.IsRunning=true;
|
||
using(var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90)))
|
||
typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!
|
||
.Invoke(model,[new SopHelper.Engine.Common.FrameResult{Size=(64,48),InferenceMs=1999},frame]);
|
||
await Task.Delay(80);
|
||
Check(model.InferenceText=="1 秒","Inference duration uses whole seconds");
|
||
model.IsRunning=false;
|
||
_exit=0;return;
|
||
}
|
||
if(Environment.GetCommandLineArgs().Contains("--sidebar-layout-only"))
|
||
{
|
||
var model=app.Container.Resolve<SopPageViewModel>();
|
||
var sidebarNavigation=app.Container.Resolve<NavigationModel>();
|
||
window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;
|
||
model.ApplyRecipeCommand.Execute();await Task.Delay(100);
|
||
var log=window.FindControl<Border>("LogPanel")!;
|
||
var navigationPanel=window.FindControl<Border>("NavigationPanel")!;
|
||
var list=log.GetVisualDescendants().OfType<ListBox>().Single();
|
||
Check(ReferenceEquals(log.DataContext,model)&&ReferenceEquals(list.ItemsSource,model.Logs),"Sidebar log shares the runtime log collection");
|
||
var view=window.GetVisualDescendants().OfType<SopPage>().Single();
|
||
var steps=view.GetVisualDescendants().OfType<Border>().Single(b=>b.Child is ScrollViewer);
|
||
foreach(var height in new[]{720,1080})
|
||
{
|
||
window.Height=height;await Task.Delay(80);window.UpdateLayout();
|
||
var logPosition=log.TranslatePoint(default,window)!.Value;
|
||
var stepsPosition=steps.TranslatePoint(default,window)!.Value;
|
||
Check(logPosition.X<180&&logPosition.Y>150&&log.Bounds.Height>200,"Log occupies the sidebar below navigation at height "+height);
|
||
Check(Math.Abs(navigationPanel.Bounds.Height-log.Bounds.Height)<1,"Navigation and log have equal heights at "+height);
|
||
Check(steps.Bounds.Height>height-500&&stepsPosition.X>logPosition.X+log.Bounds.Width,"Steps fill the released right column at height "+height);
|
||
}
|
||
model.StepCards.Clear();
|
||
var completedCard=new StepCard{StepId=1,Name="已完成步骤",IsMet=true};
|
||
var skippedCard=new StepCard{StepId=2,Name="异常跳过步骤",IsSkipped=true};
|
||
model.StepCards.Add(completedCard);model.StepCards.Add(skippedCard);
|
||
await Task.Delay(80);
|
||
var cards=steps.GetVisualDescendants().OfType<Border>().Where(b=>b.Name=="card").ToArray();
|
||
Check(cards.Length==2&&cards[0].Background is ISolidColorBrush green&&green.Color==Color.Parse("#14532D")
|
||
&&cards[1].Background is ISolidColorBrush red&&red.Color==Color.Parse("#7F1D1D"),"Completed steps render green and skipped steps render red");
|
||
var greenBackground=cards[0].Background;
|
||
completedCard.IsMet=false;skippedCard.IsSkipped=false;await Task.Delay(30);
|
||
Check(!Equals(cards[0].Background,greenBackground)&&Equals(cards[0].Background,cards[1].Background),"Reset removes completion and skip background colors");
|
||
completedCard.IsMet=true;skippedCard.IsSkipped=true;await Task.Delay(30);
|
||
var screenshots=Path.GetFullPath(Path.Combine("..","scratch","screenshots"));Directory.CreateDirectory(screenshots);
|
||
using(var rendered=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height)))
|
||
{rendered.Render(window);rendered.Save(Path.Combine(screenshots,"sidebar-log-layout.png"));}
|
||
sidebarNavigation.SelectedIndex=1;await Task.Delay(80);
|
||
Check(log.IsEffectivelyVisible&&ReferenceEquals(list.ItemsSource,model.Logs),"Sidebar log remains visible when navigating to settings");
|
||
_exit=0;return;
|
||
}
|
||
if(Environment.GetCommandLineArgs().Contains("--recipe-close-only"))
|
||
{ await CheckRecipeClose(app,lifetime);_exit=0;return; }
|
||
if(Environment.GetCommandLineArgs().Contains("--step-trigger-tabs-only"))
|
||
{ await CheckStepTriggerTabs(app,lifetime);_exit=0;return; }
|
||
if(Environment.GetCommandLineArgs().Contains("--runtime-settings-only"))
|
||
{
|
||
var model=app.Container.Resolve<SopPageViewModel>();
|
||
var view=new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(model);
|
||
var dialog=new Window{Content=view,Width=900,Height=720};dialog.Show();await Task.Delay(100);
|
||
try
|
||
{
|
||
// 旧工作区的判定超时继续生效,运行设置界面只调整其余运行参数。
|
||
RuntimeSettingsStore.Current.Save(new RuntimeOptions { DjevTimeoutMs = 375 });
|
||
model.ApplyRecipeCommand.Execute();
|
||
Check(!view.GetVisualDescendants().OfType<TextBlock>().Any(text => text.Text?.Contains("djev", StringComparison.OrdinalIgnoreCase) == true)
|
||
&& view.FindControl<NumericUpDown>("DjevTimeoutInput") is null
|
||
&& view.FindControl<ComboBox>("DjevTierInput") is null, "运行设置已移除 djev 区块");
|
||
view.GetVisualDescendants().OfType<Slider>().Single().Value=3;
|
||
view.FindControl<CheckBox>("AutoResetCheckBox")!.IsChecked=false;
|
||
view.FindControl<NumericUpDown>("ResetDelayInput")!.Value=4;
|
||
await Task.Delay(50);
|
||
var saved=RuntimeSettingsStore.Current.Read()!;
|
||
Check(model.FrameStride==3&&!model.AutoResetOnComplete&&model.ResetDelaySec==4
|
||
&&saved.FrameStride==3&&!saved.AutoResetOnComplete&&saved.ResetDelaySec==4
|
||
&&saved.DjevTimeoutMs==375,"自动保存运行参数时保留既有判定超时");
|
||
Check(new RuntimeSettingsStore(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!).Read()!.DjevTimeoutMs==375,
|
||
"新建设置存储实例仍能恢复全局djev超时");
|
||
model.ApplyRecipeCommand.Execute();
|
||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||
Check(engine.Config.Sop.Settings.FrameStride==3&&!engine.Config.Sop.Settings.AutoResetOnComplete&&engine.Config.Sop.Settings.ResetDelaySec==4&&engine.Config.Sop.Settings.DjevTimeoutMs==375,
|
||
"应用配方不会覆盖运行设置,并传给引擎");
|
||
model.IsRunning=true;await Task.Delay(30);
|
||
Check(!view.FindControl<CheckBox>("AutoResetCheckBox")!.IsEnabled&&!view.FindControl<NumericUpDown>("ResetDelayInput")!.IsEnabled,"运行中禁止修改运行参数");
|
||
model.AutoResetOnComplete=true;model.FrameStride=8;model.ResetDelaySec=20;
|
||
Check(model.FrameStride==3&&!model.AutoResetOnComplete&&model.ResetDelaySec==4,"运行中参数赋值也不会覆盖已保存设置");
|
||
model.IsRunning=false;
|
||
using var rendered=new RenderTargetBitmap(new PixelSize(900,720));rendered.Render(dialog);
|
||
var screenshots=Path.Combine(Directory.GetCurrentDirectory(),"..","scratch","screenshots");Directory.CreateDirectory(screenshots);
|
||
rendered.Save(Path.Combine(screenshots,"runtime-settings.png"));
|
||
}
|
||
finally{model.IsRunning=false;dialog.Close();}
|
||
_exit=0;return;
|
||
}
|
||
if(_agentSettingsFile is not null)
|
||
{
|
||
var model=new RecipeEditorViewModel();
|
||
var view=new RecipeEditor{DataContext=model};
|
||
var dialog=new Window{Width=1040,Height=900,Content=view};dialog.Show();
|
||
model.OnDialogOpened(new DialogParameters{{"new",true}});
|
||
view.GetVisualDescendants().OfType<TabControl>().First().SelectedIndex=4;
|
||
view.FindControl<Expander>("AgentSettingsExpander")!.IsExpanded=true;
|
||
model.FetchAgentModelsCommand.Execute();
|
||
for(var i=0;i<180&&model.AgentModels.Count==0;i++)await Task.Delay(100);
|
||
Check(model.AgentModels.Count>0,"Live editor model discovery: "+model.AgentStatus);
|
||
Console.WriteLine("Models: "+string.Join(", ",model.AgentModels));
|
||
await model.ShutdownAsync();dialog.Close();_exit=0;return;
|
||
}
|
||
if(Environment.GetCommandLineArgs().Contains("--diagnostics-only"))
|
||
{
|
||
var model=app.Container.Resolve<SopPageViewModel>();
|
||
model.ApplyRecipeCommand.Execute();await Task.Delay(80);
|
||
Check(!window.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Name=="InferenceBackend"),"Operator page hides inference backend diagnostic details");
|
||
Check(model.Logs.Any(l=>l.Message.Contains("推理设备:")&&l.Message.Contains("步骤确认=")),"Inference backend diagnostics remain available in the runtime log");
|
||
_exit=0;return;
|
||
}
|
||
if(Environment.GetCommandLineArgs().Contains("--camera-lifecycle-only")) { CheckCameraPreferences(app); await CheckCameraLifecycle(app,window); _exit=0; return; }
|
||
if(Environment.GetCommandLineArgs().Contains("--usb-capture-only")) { await CheckUsbCapture(app); _exit=0; return; }
|
||
if(Environment.GetCommandLineArgs().Contains("--agent-only"))
|
||
{ await CheckVisionConfirmation(app,app.Container.Resolve<SopPageViewModel>());_exit=0;return; }
|
||
CheckCameraPreferences(app);
|
||
CheckRecipePreferences(app);
|
||
var navigation=app.Container.Resolve<NavigationModel>();
|
||
Check(navigation.Pages.Count==2&&navigation.Pages[1].DisplayName=="设置","Sidebar contains operator and runtime settings pages only");
|
||
Check(navigation.Pages[0].DisplayName=="运行"&&!navigation.Pages.Any(p=>p.DisplayName=="零件标注与训练"),"Training no longer has a standalone sidebar entry");
|
||
window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;
|
||
await Task.Delay(150);
|
||
var sop=app.Container.Resolve<SopPageViewModel>();
|
||
// 单独验证结束图归档,便于复现归档路径和轮次问题。
|
||
if(Environment.GetCommandLineArgs().Contains("--completion-images-only")){await CheckCompletionImageSaving(app,sop);_exit=0;return;}
|
||
if(_visionOnly){await CheckVisionConfirmation(app,sop);_exit=0;return;}
|
||
var sopView=window.GetVisualDescendants().OfType<SopPage>().Single();
|
||
Check(!sopView.GetVisualDescendants().Any(c=>c is ComboBox or Slider),"Operator page contains no camera, recipe or parameter editors");
|
||
Check(sop.ActiveRecipe==sop.SelectedRecipe&&!sop.IsRunning,"Startup applies the selected recipe without starting acquisition");
|
||
Check(!string.IsNullOrWhiteSpace(sop.SelectedRecipe)&&sopView.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text==sop.SelectedRecipe),"Operator page displays the selected recipe before applying or starting");
|
||
navigation.SelectedIndex=1;await Task.Delay(100);
|
||
var settings=window.GetVisualDescendants().OfType<SopHelper.VVMs.RuntimeSettings.RuntimeSettings>().Single();
|
||
Check(ReferenceEquals(settings.DataContext,sop),"Settings and operator page share runtime state");
|
||
// 相机、配方和 djev 启动档位各有下拉,抽帧是唯一的滑块。
|
||
Check(settings.GetVisualDescendants().OfType<ComboBox>().Count()==3&&settings.GetVisualDescendants().OfType<Slider>().Count()==1,"Camera, recipe, djev tier and stride editors are on settings page");
|
||
await CheckRecipeSelection(window,navigation,sop);
|
||
if(_recipeSelectionOnly){_exit=0;return;}
|
||
// 后续断言针对 demo 的四步三域,不能依赖新增模板后的文件排序。
|
||
sop.SelectedRecipe="demo.yaml";
|
||
sop.ApplyRecipeCommand.Execute();
|
||
Check(sop.ActiveRecipe==sop.SelectedRecipe,"Applied recipe is shown as current");
|
||
var applied=sop.ActiveRecipe;var selected=sop.SelectedRecipe;
|
||
sop.SelectedRecipe="pending.yaml";
|
||
Check(sop.ActiveRecipe==applied,"Unapplied recipe selection does not change current recipe");
|
||
navigation.SelectedIndex=0;await Task.Delay(80);
|
||
Check(!window.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Name=="InferenceBackend")
|
||
&&sop.Logs.Any(l=>l.Message.Contains("推理设备:")&&l.Message.Contains("步骤确认=")),
|
||
"Inference backend diagnostics appear in logs instead of the operator page");
|
||
Check(window.GetVisualDescendants().OfType<SopPage>().Single().GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text=="pending.yaml"),"Operator page updates to the selected recipe without applying or starting");
|
||
sop.SelectedRecipe=selected;await Task.Delay(80);
|
||
Check(window.GetVisualDescendants().OfType<SopPage>().Single().GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text==selected),"Recipe selection changes notify the operator page immediately");
|
||
navigation.SelectedIndex=1;await Task.Delay(80);
|
||
Save(window,"runtime-settings");
|
||
navigation.SelectedIndex=0;await Task.Delay(100);
|
||
Check(window.GetVisualDescendants().OfType<SopPage>().Single().GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text==applied),"Operator page displays the applied recipe");
|
||
Check(sop.StepCards.Count==4&&sop.Rois.Count==3,"Original SOP recipe creates four steps and three ROIs");
|
||
sop.StartStopCommand.Execute();
|
||
for(var i=0;i<100&&!sop.IsRunning;i++)await Task.Delay(20);
|
||
Check(sop.IsRunning,"Original start command connects the shared camera/pipeline");
|
||
navigation.SelectedIndex=1;await Task.Delay(80);
|
||
Check(settings.GetVisualDescendants().Where(c=>c is ComboBox or Slider).Cast<Control>().All(c=>!c.IsEnabled),"Runtime settings cannot be edited during acquisition");
|
||
Check(!sop.DeleteRecipeCommand.CanExecute(),"Recipe deletion is disabled during acquisition");
|
||
navigation.SelectedIndex=0;await Task.Delay(80);
|
||
await Task.Run(()=>{Camera.Emit();Camera.Emit();});
|
||
await Task.Delay(150);
|
||
Check(sop.Frame is not null&&sop.FrameWidth==640&&sop.FrameHeight==480,"Camera buffer renders through the shared Avalonia bitmap adapter");
|
||
await CheckMovingPreview(sop,window);
|
||
Save(window,"sop");
|
||
sop.StartStopCommand.Execute();for(var i=0;i<100&&sop.IsRunning;i++)await Task.Delay(20);
|
||
Check(!sop.IsRunning&&Camera.IsConnected&&!Camera.IsGrabbing,"Stop command retains the idle camera connection");
|
||
await CheckProcessImages(app,sop,window);
|
||
await CheckRuntimeStatistics(app,sop,window);
|
||
await CheckCompletionImageSaving(app,sop);
|
||
if(_processImagesOnly){_exit=0;return;}
|
||
navigation.SelectedIndex=1;await Task.Delay(80);
|
||
Check(settings.GetVisualDescendants().Where(c=>c is ComboBox or Slider).Cast<Control>().All(c=>c.IsEnabled),"Runtime settings become editable after stopping");
|
||
await CheckRecipeDeletion(lifetime,settings,sop);
|
||
await CheckRecipeTransfer(lifetime,settings,sop);
|
||
navigation.SelectedIndex=0;await Task.Delay(80);
|
||
Check(window.GetVisualDescendants().OfType<SopPage>().Any(),"SOP page navigates");
|
||
sop.EditRecipeCommand.Execute();await Task.Delay(150);
|
||
var modal=lifetime.Windows.OfType<RecipeDialogWindow>().Single();
|
||
Check(modal.Width==1180&&modal.Height==880&&modal.DataContext is RecipeEditorViewModel,"Edit command opens a recipe dialog sized for embedded annotation and training");
|
||
Check(ReferenceEquals(((RecipeEditorViewModel)modal.DataContext!).SopRecording!.SelectedCamera,sop.SelectedCamera),"SOP recording inherits the runtime settings camera");
|
||
((RecipeEditorViewModel)modal.DataContext!).CloseCommand.Execute();
|
||
await ChooseRecipeClose(modal,"SaveRecipeAndCloseButton");
|
||
for(var i=0;i<100&&lifetime.Windows.Contains(modal);i++)await Task.Delay(20);
|
||
Check(!lifetime.Windows.Contains(modal),"Recipe close command respects the Prism dialog lifecycle");
|
||
sop.EditRecipeCommand.Execute();await Task.Delay(150);
|
||
var titlebarModal=lifetime.Windows.OfType<RecipeDialogWindow>().Single();titlebarModal.Close();
|
||
await ChooseRecipeClose(titlebarModal,"DiscardRecipeAndCloseButton");
|
||
for(var i=0;i<100&&lifetime.Windows.Contains(titlebarModal);i++)await Task.Delay(20);
|
||
Check(!lifetime.Windows.Contains(titlebarModal),"Titlebar close awaits SOP camera shutdown and closes the Prism dialog");
|
||
var fitted=RegionCanvas.FitImage(new Size(1000,800),new Size(1920,1080));
|
||
var pixel=RegionCanvas.ToImage(fitted.Center,fitted,new Size(1920,1080));
|
||
Check(Math.Abs(pixel.X-960)<.001&&Math.Abs(pixel.Y-540)<.001,"ROI maps letterbox center back to original pixels");
|
||
Check(RegionCanvas.PixelBounds(new Point(100,120),new Point(10,20),new Size(1920,1080))==new PixelRect(10,20,90,100),"Reverse ROI drag preserves bounds");
|
||
var pixels=new byte[]{3,17,240,29,100,31};
|
||
using(var bitmap=SopHelper.Presentation.Imaging.BitmapSource.Create(2,1,96,96,SopHelper.Presentation.Imaging.PixelFormats.Bgr24,null,pixels,6))
|
||
{
|
||
pixels[0]=255;bitmap.Save(Path.Combine(Output,"pixels.png"));
|
||
using var decoded=Cv2.ImRead(Path.Combine(Output,"pixels.png"));
|
||
Check(decoded.At<Vec3b>(0,0)==new Vec3b(3,17,240)&&decoded.At<Vec3b>(0,1)==new Vec3b(29,100,31),"Bitmap adapter owns its buffer and preserves BGR colors");
|
||
}
|
||
using(var image=SopHelper.Presentation.Imaging.BitmapSource.Create(200,100,96,96,SopHelper.Presentation.Imaging.PixelFormats.Bgr24,null,new byte[200*100*3],600))
|
||
{
|
||
var region=new RegionNode {Key="roi",X1=0,Y1=0,X2=10,Y2=10};
|
||
var canvas=new RegionCanvas {Image=image,Regions=[region],SelectedRegion=region};
|
||
var drawing=new Window {Width=400,Height=400,Content=canvas};drawing.Show();await Task.Delay(60);
|
||
drawing.MouseDown(new Point(300,250),MouseButton.Left);drawing.MouseMove(new Point(100,150));drawing.MouseUp(new Point(100,150),MouseButton.Left);
|
||
Check(region.X1==50&®ion.Y1==25&®ion.X2==150&®ion.Y2==75,"Actual ROI pointer drag excludes image letterboxing and supports reverse drawing");
|
||
drawing.Close();
|
||
}
|
||
Check(userCameraBefore is null ? !File.Exists(userCameraPath) : File.Exists(userCameraPath)&&userCameraBefore.SequenceEqual(File.ReadAllBytes(userCameraPath)),"Smoke tests leave the real user's camera preference unchanged");
|
||
File.WriteAllText(Path.Combine(Output,"result.json"),JsonSerializer.Serialize(new {passed=true,pages=navigation.Pages.Select(p=>p.DisplayName)}));
|
||
_exit=0;
|
||
}
|
||
catch(Exception ex){Console.Error.WriteLine(ex);}
|
||
finally{lifetime.Shutdown(_exit);}
|
||
}
|
||
private static async Task CheckRecipeDeletion(IClassicDesktopStyleApplicationLifetime lifetime,Control settings,SopPageViewModel sop)
|
||
{
|
||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
var name="delete-test-"+Guid.NewGuid().ToString("N");var file=name+".yaml";
|
||
var directory=store.DirectoryFor(name);Directory.CreateDirectory(directory);
|
||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
|
||
config.Sop.Steps=[new SopHelper.Engine.Sop.StepDef{Id=1,Name="删除检查",Detection=new SopHelper.Engine.Sop.StepCondition{Method=SopHelper.Engine.Sop.ConditionMethod.TimeElapsed}}];
|
||
SopHelper.Engine.Sop.SopConfigLoader.Save(config,store.ConfigPath(name));
|
||
foreach(var folder in new[]{"recordings","parts","models","sop_stand"})
|
||
{Directory.CreateDirectory(Path.Combine(directory,folder));File.WriteAllText(Path.Combine(directory,folder,"keep.bin"),folder);}
|
||
var selected=sop.SelectedRecipe;sop.Recipes.Add(file);sop.SelectedRecipe=file;
|
||
var button=settings.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="删除");
|
||
Check(ReferenceEquals(button.Command,sop.DeleteRecipeCommand)&&button.Command!.CanExecute(null),"Runtime settings exposes a working delete recipe button");
|
||
var confirm=sop.ConfirmDeleteRecipeAsync;sop.ConfirmDeleteRecipeAsync=null;sop.DeleteRecipeCommand.Execute();
|
||
Check(File.Exists(store.ConfigPath(name)),"Deleting without a confirmation handler cannot remove a recipe");sop.ConfirmDeleteRecipeAsync=confirm;
|
||
sop.DeleteRecipeCommand.Execute();await Task.Delay(50);
|
||
var popup=lifetime.Windows.OfType<SopHelper.VVMs.RuntimeSettings.DeleteRecipeDialog>().Single();
|
||
Check(File.Exists(store.ConfigPath(name))&&popup.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text?.Contains(name)==true),"Deletion confirmation identifies the recipe before any files move");
|
||
Save(popup,"delete-recipe-confirm");popup.Close(false);await Task.Delay(40);
|
||
Check(File.Exists(store.ConfigPath(name))&&sop.SelectedRecipe==file,"Cancelling deletion leaves the selected recipe and its data intact");
|
||
sop.DeleteRecipeCommand.Execute();await Task.Delay(50);
|
||
popup=lifetime.Windows.OfType<SopHelper.VVMs.RuntimeSettings.DeleteRecipeDialog>().Single();
|
||
// A queued editor-save callback may apply a recipe while its deletion is being confirmed.
|
||
sop.ApplyRecipeCommand.Execute();Check(sop.ActiveRecipe==file&&sop.StepCards.Count==1,"Recipe becomes active while deletion confirmation is open");
|
||
popup.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="确认删除").RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
await Task.Delay(100);
|
||
Check(!Directory.Exists(directory)&&!sop.Recipes.Contains(file)&&sop.SelectedRecipe!=file,"Confirmed deletion removes the recipe and refreshes the selection");
|
||
Check(sop.ActiveRecipe=="未应用配方"&&sop.StepCards.Count==0&&sop.Rois.Count==0,"Deleting the active recipe clears its runtime state");
|
||
Check(settings.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text==sop.StatusText),"Deletion feedback is visible in runtime settings");
|
||
var archive=Directory.GetDirectories(Path.Combine(store.DeletedRecipesDirectory,name)).Single();
|
||
Check(File.Exists(Path.Combine(archive,file))&&new[]{"recordings","parts","models","sop_stand"}.All(folder=>File.ReadAllText(Path.Combine(archive,folder,"keep.bin"))==folder),"Deletion preserves all recipe data in a local archive");
|
||
var preference=Path.Combine(store.Root,"workspace","last-recipe.json");
|
||
Check(JsonSerializer.Deserialize<string>(File.ReadAllText(preference))==sop.SelectedRecipe,"Deletion updates the remembered recipe selection");
|
||
sop.SelectedRecipe=null;Check(!sop.DeleteRecipeCommand.CanExecute(),"An empty selection cannot be deleted");
|
||
Check(!sop.StartStopCommand.CanExecute(),"Acquisition cannot start with an empty recipe selection");
|
||
sop.SelectedRecipe=selected;
|
||
}
|
||
|
||
/// <summary>验证配方导入导出入口、同名确认窗的选择回传和说明文案;文件选择器不在无头环境调用。</summary>
|
||
private static async Task CheckRecipeTransfer(IClassicDesktopStyleApplicationLifetime lifetime, Control settings, SopPageViewModel sop)
|
||
{
|
||
var store = new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
var importButton = settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content?.ToString() == "导入");
|
||
var exportButton = settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content?.ToString() == "导出");
|
||
// Excel 导出紧跟打开文件夹并使用与配方包导出一致的选择条件。
|
||
var openFolderButton = settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content?.ToString() == "打开文件夹");
|
||
var recipeActions = (WrapPanel)openFolderButton.Parent!;
|
||
Check(recipeActions.Children[recipeActions.Children.IndexOf(openFolderButton) + 1] is Button sopButton
|
||
&& Equals(sopButton.Content, "导出SOP文件") && ReferenceEquals(sopButton.Command, sop.ExportSopCommand)
|
||
&& sop.ExportSopCommand.CanExecute(), "运行设置的打开文件夹后提供 SOP Excel 导出");
|
||
Check(ReferenceEquals(importButton.Command, sop.ImportRecipeCommand) && ReferenceEquals(exportButton.Command, sop.ExportRecipeCommand)
|
||
&& importButton.Command!.CanExecute(null) && exportButton.Command!.CanExecute(null), "运行设置提供可用的配方导入导出按钮");
|
||
Check(ToolTip.GetTip(exportButton)?.ToString()?.Contains(".bwsrecipe") == true
|
||
&& ToolTip.GetTip(importButton)?.ToString()?.Contains("再应用") == true,
|
||
"运行设置说明配方包内容与导入不会自动应用");
|
||
var selected = sop.SelectedRecipe;
|
||
sop.SelectedRecipe = null;
|
||
Check(sop.ImportRecipeCommand.CanExecute() && !sop.ExportRecipeCommand.CanExecute() && !sop.ExportSopCommand.CanExecute(), "空配方选择仍可导入但不能导出");
|
||
sop.SelectedRecipe = selected;
|
||
|
||
var name = "transfer-" + Guid.NewGuid().ToString("N");
|
||
Directory.CreateDirectory(store.DirectoryFor(name));
|
||
var config = new SopHelper.Engine.Sop.SopConfig(); config.Sop.Name = name;
|
||
config.Sop.Steps = [new SopHelper.Engine.Sop.StepDef { Id = 1, Name = "导入检查", Description = "步骤说明", Detection = new SopHelper.Engine.Sop.StepCondition { Method = SopHelper.Engine.Sop.ConditionMethod.TimeElapsed } }];
|
||
SopHelper.Engine.Sop.SopConfigLoader.Save(config, store.ConfigPath(name));
|
||
var package = SopHelper.Engine.Recipes.RecipePackage.Export(store, name, Path.Combine(store.Root, name)).Path;
|
||
var directories = Directory.GetDirectories(store.RecipesDirectory).Length;
|
||
var info = SopHelper.Engine.Recipes.RecipePackage.Inspect(package);
|
||
var prompt = new SopPageViewModel.ImportConflict(package, info, name + "-2");
|
||
var confirm = sop.ConfirmImportConflictAsync ?? throw new Exception("运行设置未接上同名配方确认");
|
||
void Click(string label) => lifetime.Windows.OfType<SopHelper.VVMs.RuntimeSettings.ImportRecipeConflictDialog>().Single()
|
||
.GetVisualDescendants().OfType<Button>().Single(b => b.Content?.ToString() == label).RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
|
||
var cancel = confirm(prompt);
|
||
await Task.Delay(60);
|
||
var dialog = lifetime.Windows.OfType<SopHelper.VVMs.RuntimeSettings.ImportRecipeConflictDialog>().Single();
|
||
Check(dialog.Title == "导入配方" && dialog.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.Contains(name) == true), "同名配方确认窗指明受影响的配方");
|
||
Check(dialog.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.Contains("已删除配方") == true), "确认窗说明覆盖前会归档现有配方");
|
||
Check(dialog.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == $"另存为“{name}-2”"), "确认窗给出改名导入的目标名称");
|
||
Click("取消");
|
||
Check(await cancel == SopPageViewModel.ImportConflictChoice.Cancel && Directory.GetDirectories(store.RecipesDirectory).Length == directories,
|
||
"确认窗取消时返回取消且不改动配方目录");
|
||
|
||
var overwrite = confirm(prompt);
|
||
await Task.Delay(60);
|
||
Click("覆盖现有配方");
|
||
Check(await overwrite == SopPageViewModel.ImportConflictChoice.Overwrite, "选择覆盖时返回覆盖");
|
||
var saveAsNew = confirm(prompt);
|
||
await Task.Delay(60);
|
||
Click($"另存为“{name}-2”");
|
||
Check(await saveAsNew == SopPageViewModel.ImportConflictChoice.SaveAsNew, "选择改名时返回另存新名");
|
||
|
||
// 直接取消导入不应由视图模型自行决定覆盖:确认钩子缺失时按取消处理。
|
||
var hook = sop.ConfirmImportConflictAsync; sop.ConfirmImportConflictAsync = null;
|
||
Check(true, "同名配方确认钩子可由运行设置提供,视图模型不自行覆盖配方");
|
||
sop.ConfirmImportConflictAsync = hook;
|
||
File.Delete(package);
|
||
store.Delete(name);
|
||
}
|
||
|
||
private static async Task CheckRecipeSelection(Window window,NavigationModel navigation,SopPageViewModel sop)
|
||
{
|
||
ComboBox RecipeBox()=>window.GetVisualDescendants().OfType<ComboBox>().Single(c=>ReferenceEquals(c.ItemsSource,sop.Recipes));
|
||
void Reload(string? preferred)=>typeof(SopPageViewModel).GetMethod("LoadRecipes",System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.NonPublic)!.Invoke(sop,[preferred]);
|
||
var selected=sop.SelectedRecipe;
|
||
Check(selected is not null&&Equals(RecipeBox().SelectedItem,selected),"Runtime settings initially displays its selected recipe");
|
||
for(var i=0;i<3;i++)
|
||
{
|
||
navigation.SelectedIndex=0;await Task.Delay(30);
|
||
Reload(selected);
|
||
navigation.SelectedIndex=1;await Task.Delay(30);
|
||
Check(sop.SelectedRecipe==selected&&Equals(RecipeBox().SelectedItem,selected),"Recipe selection survives list refresh while runtime settings is hidden");
|
||
Reload(selected);
|
||
await Task.Delay(30);
|
||
Check(sop.SelectedRecipe==selected&&Equals(RecipeBox().SelectedItem,selected),"Recipe selection survives list refresh while runtime settings is visible");
|
||
}
|
||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
var name="000-selection-"+Guid.NewGuid().ToString("N");
|
||
Directory.CreateDirectory(store.DirectoryFor(name));
|
||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
|
||
SopHelper.Engine.Sop.SopConfigLoader.Save(config,store.ConfigPath(name));
|
||
try
|
||
{
|
||
navigation.SelectedIndex=0;await Task.Delay(30);Reload(selected);
|
||
navigation.SelectedIndex=1;await Task.Delay(30);
|
||
Check(sop.Recipes.Contains(name+".yaml")&&Equals(RecipeBox().SelectedItem,selected),"Adding a recipe before the selected item preserves the visible selection");
|
||
navigation.SelectedIndex=0;await Task.Delay(30);Reload(name+".yaml");
|
||
navigation.SelectedIndex=1;await Task.Delay(30);
|
||
Check(sop.SelectedRecipe==name+".yaml"&&Equals(RecipeBox().SelectedItem,sop.SelectedRecipe),"Saving a new recipe while settings is hidden selects it on return");
|
||
navigation.SelectedIndex=0;await Task.Delay(30);File.Delete(store.ConfigPath(name));Reload(null);
|
||
navigation.SelectedIndex=1;await Task.Delay(30);
|
||
Check(sop.SelectedRecipe is not null&&sop.SelectedRecipe!=name+".yaml"&&Equals(RecipeBox().SelectedItem,sop.SelectedRecipe),"Removing the selected recipe while settings is hidden displays the fallback recipe");
|
||
}
|
||
finally
|
||
{
|
||
if(File.Exists(store.ConfigPath(name)))File.Delete(store.ConfigPath(name));
|
||
Directory.Delete(store.DirectoryFor(name));Reload(selected);
|
||
}
|
||
}
|
||
|
||
private static void CheckRecipePreferences(App app)
|
||
{
|
||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
var path=Path.Combine(store.Root,"workspace","last-recipe.json");
|
||
var before=File.Exists(path)?File.ReadAllBytes(path):null;
|
||
var name="preferred-recipe-"+Guid.NewGuid().ToString("N");
|
||
var file=name+".yaml";var directory=store.DirectoryFor(name);
|
||
Directory.CreateDirectory(directory);
|
||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
|
||
config.Sop.Regions["work"]=new(){X2=64,Y2=48};
|
||
config.Sop.Steps.Add(new(){Id=1,Name="启动步骤",Detection=new(){Method="object_present",TargetObject="part"}});
|
||
SopHelper.Engine.Sop.SopConfigLoader.Save(config,store.ConfigPath(name));
|
||
void WithVm(Action<SopPageViewModel> check)
|
||
{
|
||
using var camera=new FakeCamera{Devices=[]};
|
||
using var pipeline=new SopHelper.Engine.Pipeline.DetectionPipeline(camera);
|
||
var vm=new SopPageViewModel(camera,pipeline,new SopHelper.Engine.Sop.SopEngine(),app.Container.Resolve<IDialogService>());
|
||
try{check(vm);}finally{vm.Destroy();}
|
||
}
|
||
try
|
||
{
|
||
WithVm(vm=>
|
||
{
|
||
Check(vm.Recipes[0]!=file,"Preference test chooses a recipe other than the first list entry");
|
||
vm.SelectedRecipe=file;
|
||
Check(JsonSerializer.Deserialize<string>(File.ReadAllText(path))==file&&!vm.IsRunning,"Selecting a recipe persists immediately without applying or starting");
|
||
vm.SelectedRecipe=null;vm.SelectedRecipe="not-a-recipe.yaml";
|
||
Check(JsonSerializer.Deserialize<string>(File.ReadAllText(path))==file,"Transient empty and invalid selections do not overwrite the saved recipe");
|
||
});
|
||
WithVm(vm=>Check(vm.SelectedRecipe==file&&vm.ActiveRecipe==file&&!vm.IsRunning
|
||
&&vm.StepCards.Single().Name=="启动步骤"&&vm.Rois.Single().Name=="work","Restart restores and applies the preferred recipe including steps and regions without acquisition"));
|
||
File.WriteAllText(store.ConfigPath(name),"sop: [invalid yaml");
|
||
WithVm(vm=>Check(vm.SelectedRecipe==file&&vm.ActiveRecipe=="未应用配方"&&!vm.IsRunning
|
||
&&vm.StatusText.Contains("自动应用配方失败"),"An invalid startup recipe reports its application failure without crashing or acquiring"));
|
||
File.Delete(store.ConfigPath(name));
|
||
WithVm(vm=>Check(vm.SelectedRecipe is not null&&vm.Recipes.Contains(vm.SelectedRecipe)&&vm.SelectedRecipe!=file&&vm.ActiveRecipe==vm.SelectedRecipe&&!vm.IsRunning,"A deleted preferred recipe falls back to and applies an available recipe"));
|
||
File.WriteAllText(path,"{invalid-json");
|
||
WithVm(vm=>Check(vm.SelectedRecipe is not null&&vm.Recipes.Contains(vm.SelectedRecipe)&&vm.ActiveRecipe==vm.SelectedRecipe,"Corrupt recipe preference still applies an available recipe"));
|
||
}
|
||
finally
|
||
{
|
||
if(before is not null)File.WriteAllBytes(path,before);else if(File.Exists(path))File.Delete(path);
|
||
File.Delete(store.ConfigPath(name));Directory.Delete(directory);
|
||
}
|
||
}
|
||
|
||
private static void CheckCameraPreferences(App app)
|
||
{
|
||
var path=Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!,"workspace","last-camera.json");
|
||
var before=File.Exists(path)?File.ReadAllBytes(path):null;
|
||
var first=new CameraInfo {Index=0,Name="测试相机"};
|
||
var preferred=new CameraInfo {Kind=CameraKind.Uvc,Index=1,Name="首选相机"};
|
||
void WithCameras(List<CameraInfo> devices,Action<SopPageViewModel,FakeCamera> check)
|
||
{
|
||
using var camera=new FakeCamera {Devices=devices};
|
||
using var pipeline=new SopHelper.Engine.Pipeline.DetectionPipeline(camera);
|
||
var vm=new SopPageViewModel(camera,pipeline,new SopHelper.Engine.Sop.SopEngine(),app.Container.Resolve<IDialogService>());
|
||
try {check(vm,camera);} finally {vm.Destroy();}
|
||
}
|
||
try
|
||
{
|
||
if(File.Exists(path))File.Delete(path);
|
||
WithCameras([first,preferred],(vm,_)=>
|
||
{
|
||
vm.SelectedCamera=preferred;
|
||
Check(!vm.IsRunning&&JsonSerializer.Deserialize<CameraInfo>(File.ReadAllText(path))!.Index==preferred.Index,"Changing camera saves immediately without starting acquisition");
|
||
});
|
||
var reindexed=new CameraInfo {Kind=preferred.Kind,Index=preferred.Index,Name=preferred.Name};
|
||
WithCameras([reindexed,first],(vm,_)=>Check(ReferenceEquals(vm.SelectedCamera,reindexed),"Restart restores the selected USB camera by index despite enumeration order changes"));
|
||
var saved=File.ReadAllText(path);
|
||
WithCameras([first],(vm,camera)=>
|
||
{
|
||
Check(vm.SelectedCamera is null&&File.ReadAllText(path)==saved,"Missing preferred camera is not silently replaced or overwritten");
|
||
camera.Devices=[];vm.RefreshCamerasCommand.Execute();
|
||
Check(vm.SelectedCamera is null&&File.ReadAllText(path)==saved,"An empty enumeration preserves camera preference");
|
||
camera.Devices=[first,reindexed];vm.RefreshCamerasCommand.Execute();
|
||
Check(ReferenceEquals(vm.SelectedCamera,reindexed),"Refreshing after reconnection restores the preferred camera");
|
||
vm.SelectedCamera=first;
|
||
});
|
||
WithCameras([reindexed,first],(vm,_)=>Check(ReferenceEquals(vm.SelectedCamera,first),"Switching camera without starting is restored on the next launch"));
|
||
File.WriteAllText(path,"{\"Kind\":1,\"Index\":9,\"Name\":\"旧设备\"}");
|
||
WithCameras([first,reindexed],(vm,_)=>Check(ReferenceEquals(vm.SelectedCamera,first),"A retired camera preference falls back to the first USB camera"));
|
||
}
|
||
finally
|
||
{
|
||
if(before is not null)File.WriteAllBytes(path,before);
|
||
else if(File.Exists(path))File.Delete(path);
|
||
}
|
||
}
|
||
private static string Output {get{var p=Path.GetFullPath("../scratch/screenshots");Directory.CreateDirectory(p);return p;}}
|
||
private static async Task CheckMovingPreview(SopPageViewModel sop,Window window)
|
||
{
|
||
var image=window.GetVisualDescendants().OfType<SopPage>().Single()
|
||
.GetVisualDescendants().OfType<Image>().Single(i=>ReferenceEquals(i.Source,sop.Frame));
|
||
var changes=0;
|
||
System.ComponentModel.PropertyChangedEventHandler onChanged=(_,e)=>{if(e.PropertyName==nameof(sop.Frame))changes++;};
|
||
sop.PropertyChanged+=onChanged;
|
||
try
|
||
{
|
||
foreach(var x in new[]{40,240,40})
|
||
{
|
||
var previous=sop.Frame;
|
||
await Task.Run(()=>Camera.Emit(x));
|
||
for(var i=0;i<50&&ReferenceEquals(previous,sop.Frame);i++)await Task.Delay(20);
|
||
Check(!ReferenceEquals(previous,sop.Frame)&&ReferenceEquals(image.Source,sop.Frame),
|
||
"Each moving frame updates the bound Image source even at the same resolution");
|
||
using var rendered=new RenderTargetBitmap(new PixelSize(640,480));
|
||
var preview=new Image {Source=sop.Frame,Width=640,Height=480};
|
||
preview.Measure(new Size(640,480));preview.Arrange(new Avalonia.Rect(0,0,640,480));
|
||
rendered.Render(preview);
|
||
var path=Path.Combine(Output,"motion-"+changes+".png");rendered.Save(path);
|
||
using var decoded=Cv2.ImRead(path);
|
||
var clearedX=x==40?260:60;
|
||
Check(decoded.At<Vec3b>(60,x+20)==new Vec3b(0,0,255)&&decoded.At<Vec3b>(60,clearedX)==new Vec3b(35,60,90),
|
||
"Moving object renders at its new position and clears its previous position");
|
||
}
|
||
Check(changes==3,"All three same-size frames notify the UI");
|
||
var last=sop.Frame;await Task.Delay(120);
|
||
Check(ReferenceEquals(last,sop.Frame),"No new camera frame leaves the displayed image intact");
|
||
}
|
||
finally{sop.PropertyChanged-=onChanged;}
|
||
}
|
||
private static async Task CheckProcessImages(App app,SopPageViewModel sop,Window window)
|
||
{
|
||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||
var config=new SopHelper.Engine.Sop.SopConfig();
|
||
config.Sop.Settings.AutoResetOnComplete=false;
|
||
config.Sop.Settings.StableFrames=1;
|
||
for(var id=1;id<=2;id++)config.Sop.Steps.Add(new()
|
||
{
|
||
Id=id,Name="过程图测试"+id,
|
||
Detection=new(){Method="time_elapsed",DurationMs=1,StableFrames=1}
|
||
});
|
||
engine.Load(config);
|
||
sop.StepCards.Clear();
|
||
foreach(var step in config.Sop.Steps)sop.StepCards.Add(new(){StepId=step.Id,Name=step.Name});
|
||
sop.IsRunning=true;engine.Start();
|
||
var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
|
||
try
|
||
{
|
||
Check(sop.StepCards.All(c=>c.IsWaitingForImage),"Every step starts with an empty process image slot");
|
||
for(var id=1;id<=2;id++)
|
||
{
|
||
await Task.Delay(20);
|
||
using(var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(id*30,60,90)))
|
||
receive.Invoke(sop,[new SopHelper.Engine.Common.FrameResult {FrameId=id,Size=(64,48)},frame]);
|
||
await Task.Delay(50);
|
||
Check(sop.StepCards[id-1].HasCompletionImage,"Completed step receives its own image");
|
||
if(id==1)Check(sop.StepCards[1].IsWaitingForImage,"Future step remains empty");
|
||
}
|
||
Check(engine.State==SopHelper.Engine.Sop.EngineState.Completed&&sop.StepCards.All(c=>c.HasCompletionImage),"Round completion retains every process image");
|
||
for(var id=1;id<=2;id++)
|
||
{
|
||
var path=Path.Combine(Output,"process-step-"+id+".png");sop.StepCards[id-1].CompletionImage!.Save(path);
|
||
using var decoded=Cv2.ImRead(path);
|
||
Check(decoded.At<Vec3b>(0,0)==new Vec3b((byte)(id*30),60,90),"Process image preserves the exact judged frame after source disposal");
|
||
}
|
||
Save(window,"process-images");
|
||
var panel=window.GetVisualDescendants().OfType<Border>().Single(b=>b.Name=="ProcessImagesPanel");
|
||
Check(panel.Bounds.Height>100&&panel.GetVisualDescendants().OfType<Image>().Count()==2,"Bottom panel renders one image card per step");
|
||
engine.Reset();
|
||
Check(sop.StepCards.All(c=>c.IsWaitingForImage),"Reset clears process images for the next round");
|
||
}
|
||
finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
|
||
}
|
||
private static async Task CheckRemainingWindowProgress(App app,Window window)
|
||
{
|
||
var model=app.Container.Resolve<SopPageViewModel>();
|
||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
const string name="剩余检查时间测试";
|
||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
|
||
for(var id=1;id<=3;id++)config.Sop.Steps.Add(new(){Id=id,Name="步骤"+id,Description="零件到位",SaveCompletionImage=false,
|
||
Detection=new(){Method="time_elapsed",DurationMs=1,StableFrames=1},
|
||
AiConfirmation=new(){ImageMode="full_frame",CheckWindowMs=10000,RetryDelayMs=50}});
|
||
Directory.CreateDirectory(store.DirectoryFor(name));SopHelper.Engine.Sop.SopConfigLoader.Save(config,store.ConfigPath(name));
|
||
model.Recipes.Add(name+".yaml");model.SelectedRecipe=name+".yaml";model.ApplyRecipeCommand.Execute();
|
||
engine.Config.Sop.Settings.AutoResetOnComplete=false;
|
||
var client=new UiVisionDecision();engine.VisionDecisionClient=client;
|
||
var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
|
||
var frameId=0;
|
||
async Task Emit(double seconds)
|
||
{
|
||
using var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90));
|
||
receive.Invoke(model,[new SopHelper.Engine.Common.FrameResult{FrameId=frameId++,SourceSeconds=seconds,
|
||
Timestamp=DateTime.UnixEpoch.AddSeconds(seconds),Size=(64,48)},frame]);
|
||
await Task.Delay(20);
|
||
}
|
||
model.IsRunning=true;engine.Start();
|
||
Check(engine.GetCheckWindowProgress(1) is null&&model.StepCards.All(c=>!c.ShowRemainingCheckTime),"No remaining-time background appears before the check window starts");
|
||
for(var i=0;i<10&&!model.StepCards[0].ShowRemainingCheckTime;i++)await Emit(0);
|
||
Check(model.StepCards[0].ShowRemainingCheckTime&&model.StepCards[0].RemainingCheckFraction>.95,"Triggered window starts with a full remaining-time background");
|
||
var before=model.StepCards[0].RemainingCheckFraction;await Task.Delay(150);
|
||
Check(model.StepCards[0].RemainingCheckFraction<before,"Remaining-time background refreshes even between incoming frames");
|
||
await Emit(5);
|
||
Check(Math.Abs(model.StepCards[0].RemainingCheckFraction-.5)<.02&&engine.GetCheckWindowProgress(1) is {TotalMs:10000},"Background tracks the engine's actual remaining check time");
|
||
Check(!model.StepCards[1].ShowRemainingCheckTime&&engine.GetCheckWindowProgress(2) is null,"Future steps do not consume the current step's window");
|
||
var view=window.GetVisualDescendants().OfType<SopPage>().Single();window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;window.UpdateLayout();
|
||
var card=view.GetVisualDescendants().OfType<Border>().First(b=>b.Name=="card");
|
||
var fill=card.GetVisualDescendants().OfType<Border>().Single(b=>b.Name=="RemainingCheckFill");
|
||
Check(fill.IsEffectivelyVisible&&fill.Bounds.Width>card.Bounds.Width*.4&&fill.Bounds.Width<card.Bounds.Width*.6
|
||
&&fill.Bounds.Height>card.Bounds.Height-6,"Remaining-time fill spans the card background with proportional width");
|
||
var cardTexts=card.GetVisualDescendants().OfType<TextBlock>().Select(t=>t.Text).ToArray();
|
||
Check(!cardTexts.Contains(model.StepCards[0].Message)&&!cardTexts.Contains("已跳过/未通过")&&cardTexts.Contains("步骤1"),"Step names are displayed without decision hints or skip text");
|
||
await Emit(12);
|
||
Check(model.StepCards[0].IsSkipped&&!model.StepCards[0].ShowRemainingCheckTime&&model.StepCards[0].AbnormalCount==1,"Window expiry still skips the step and replaces the background with its abnormal state");
|
||
client=new UiVisionDecision();engine.VisionDecisionClient=client;
|
||
for(var i=0;i<10&&!client.Called.Task.IsCompleted;i++)await Emit(12.1);
|
||
Check(client.Called.Task.IsCompleted,"The following step keeps the normal retry-and-check workflow");
|
||
client.Result.SetResult(new(true,.99,"确认完成"));
|
||
for(var i=0;i<10&&engine.CurrentStep?.Id==2;i++)await Emit(12.2);
|
||
Check(model.StepCards[1].IsMet&&!model.StepCards[1].ShowRemainingCheckTime&&model.StepCards[1].NormalCount==1,"Confirmed steps keep their completed background and normal count");
|
||
engine.VisionDecisionClient=new UiVisionDecision();
|
||
for(var i=0;i<10&&!model.StepCards[2].ShowRemainingCheckTime;i++)await Emit(12.3);
|
||
await Emit(17.3);await Task.Delay(40);window.UpdateLayout();
|
||
var screenshots=Path.GetFullPath(Path.Combine("..","scratch","screenshots"));Directory.CreateDirectory(screenshots);
|
||
using(var rendered=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height)))
|
||
{rendered.Render(window);rendered.Save(Path.Combine(screenshots,"remaining-check-background.png"));}
|
||
engine.Stop();model.IsRunning=false;await Task.Delay(120);
|
||
Check(model.StepCards.All(c=>!c.ShowRemainingCheckTime),"Stopping clears active progress without leaving a stale time background");
|
||
engine.Reset();await Task.Delay(30);
|
||
Check(model.StepCards.All(c=>!c.ShowRemainingCheckTime)&&model.StepCards[0].AbnormalCount==1&&model.StepCards[1].NormalCount==1,"Reset clears progress while preserving accumulated results");
|
||
engine.Stop();
|
||
}
|
||
|
||
/// <summary>通过主界面验证标准视频切换检测来源,以及停止与播放失败时释放文件。</summary>
|
||
private static async Task CheckStandardSopPlayback(App app,Window window)
|
||
{
|
||
var model=app.Container.Resolve<SopPageViewModel>();
|
||
var view=window.GetVisualDescendants().OfType<SopPage>().Single();
|
||
var texts=view.GetVisualDescendants().OfType<TextBlock>().Select(t=>t.Text).ToArray();
|
||
Check(!texts.Contains("步骤计时")&&texts.Contains("流程计时")&&texts.Contains("标准用时"),"Header retains flow and standard times without step timing");
|
||
var buttons=view.GetVisualDescendants().OfType<Button>().ToArray();
|
||
Check(!buttons.Any(b=>b.Content?.ToString() is "暂停" or "重置步骤")
|
||
&&buttons.Any(b=>b.Content?.ToString()=="重置计数"),"Main run controls remove pause and step reset while keeping count reset");
|
||
// 使用独立配方,避免随程序分发的示例视频影响无视频状态。
|
||
var store = new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
const string recipe = "standard-video-smoke";
|
||
var config = new SopConfig();
|
||
config.Sop.Name = recipe;
|
||
Directory.CreateDirectory(store.DirectoryFor(recipe));
|
||
SopConfigLoader.Save(config, store.ConfigPath(recipe));
|
||
model.Recipes.Add(recipe + ".yaml");
|
||
model.SelectedRecipe = recipe + ".yaml";
|
||
model.ApplyRecipeCommand.Execute();
|
||
await Task.Delay(30);
|
||
var play=view.FindControl<Button>("PlayStandardSopButton")!;
|
||
Check(!play.IsEffectivelyEnabled,"Standard SOP playback is unavailable when no standard video exists");
|
||
var path=Path.Combine(store.DirectoryFor(recipe),"sop_stand","sop.avi");
|
||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||
using(var writer=new VideoWriter(path,FourCC.MJPG,10,new OpenCvSharp.Size(160,120)))
|
||
{
|
||
Check(writer.IsOpened(),"Standard SOP playback fixture opens");
|
||
for(var i=0;i<40;i++)
|
||
{
|
||
using var frame=new Mat(120,160,MatType.CV_8UC3,new Scalar(40+i*3,70,120));
|
||
Cv2.PutText(frame,"SOP "+i,new OpenCvSharp.Point(15,65),HersheyFonts.HersheySimplex,.6,new Scalar(255,255,255),1);
|
||
writer.Write(frame);
|
||
}
|
||
}
|
||
model.ApplyRecipeCommand.Execute();await Task.Delay(30);
|
||
Check(play.IsEffectivelyEnabled,"Applying a recipe with a saved standard video enables playback");
|
||
model.StartStopCommand.Execute();for(var i=0;i<100&&!model.IsRunning;i++)await Task.Delay(20);
|
||
Check(model.IsRunning && Camera.IsGrabbing, "播放前相机正在采集");
|
||
var cameraConnections = Camera.ConnectCount;
|
||
play.Command!.Execute(play.CommandParameter);
|
||
bool VideoFrameShown() => model.PreviewFrame is SopHelper.Presentation.Imaging.BitmapSource { PixelWidth: 160, PixelHeight: 120 };
|
||
for (var i = 0; i < 100 && !VideoFrameShown(); i++) await Task.Delay(20);
|
||
Check(model.IsRunning && !Camera.IsGrabbing && Camera.ConnectCount == cameraConnections
|
||
&& model.StandardSopButtonText == "停止标准 SOP" && VideoFrameShown(),
|
||
"主界面切换到标准视频画面并运行检测");
|
||
var screenshots = Path.GetFullPath(Path.Combine("..", "scratch", "screenshots"));
|
||
Directory.CreateDirectory(screenshots);
|
||
window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;await Task.Delay(50);window.UpdateLayout();
|
||
using(var rendered=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height)))
|
||
{rendered.Render(window);rendered.Save(Path.Combine(screenshots,"standard-sop-main.png"), PngBitmapEncoderOptions.Default);}
|
||
play.Command.Execute(play.CommandParameter);
|
||
for (var i = 0; i < 100 && model.IsRunning; i++) await Task.Delay(20);
|
||
Check(!model.IsRunning && model.StatusText == "已停止标准 SOP 播放", "停止标准视频时同步结束检测");
|
||
using (var exclusive = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||
Check(exclusive.Length > 0, "停止播放后释放视频文件");
|
||
|
||
File.WriteAllText(path, "damaged-video");
|
||
play.Command.Execute(play.CommandParameter);
|
||
for (var i = 0; i < 100 && (model.IsRunning || !model.Logs.Any(item => item.Message.StartsWith("标准 SOP 播放或检测失败"))); i++) await Task.Delay(20);
|
||
Check(!model.IsRunning && !Camera.IsGrabbing && model.StandardSopButtonText == "播放标准 SOP"
|
||
&& model.Logs.Any(item => item.Message.StartsWith("标准 SOP 播放或检测失败")),
|
||
"无法打开标准视频时结束检测并恢复播放入口");
|
||
}
|
||
|
||
private static async Task CheckStepCounts(App app,Window window)
|
||
{
|
||
var model=app.Container.Resolve<SopPageViewModel>();
|
||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
const string name="步骤次数测试";
|
||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
|
||
for(var id=1;id<=2;id++)config.Sop.Steps.Add(new(){Id=id,Name="步骤"+id,Description="零件已放好",SaveCompletionImage=false,
|
||
Detection=new(){Method="time_elapsed",DurationMs=1,StableFrames=1},
|
||
AiConfirmation=new(){ImageMode="full_frame",EvidenceMode=id==1?"single_frame":"sequence",CheckWindowMs=0}});
|
||
Directory.CreateDirectory(store.DirectoryFor(name));SopHelper.Engine.Sop.SopConfigLoader.Save(config,store.ConfigPath(name));
|
||
model.Recipes.Add(name+".yaml");model.SelectedRecipe=name+".yaml";model.ApplyRecipeCommand.Execute();
|
||
engine.Config.Sop.Settings.AutoResetOnComplete=false;
|
||
var decision=new UiVisionDecision();engine.VisionDecisionClient=decision;
|
||
var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
|
||
async Task Emit()
|
||
{
|
||
using(var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90)))
|
||
receive.Invoke(model,[new SopHelper.Engine.Common.FrameResult{Size=(64,48)},frame]);
|
||
await Task.Delay(20);
|
||
}
|
||
void Counts(long n1,long a1,long n2,long a2,string message)=>Check(
|
||
model.StepCards[0].NormalCount==n1&&model.StepCards[0].AbnormalCount==a1
|
||
&&model.StepCards[1].NormalCount==n2&&model.StepCards[1].AbnormalCount==a2,message);
|
||
model.IsRunning=true;engine.Start();
|
||
for(var i=0;i<10&&!decision.Called.Task.IsCompleted;i++)await Emit();
|
||
Check(decision.Called.Task.IsCompleted,"A real engine step submits its decision");
|
||
await Emit();await Emit();Counts(0,0,0,0,"Waiting and repeated frame snapshots do not increment step counts");
|
||
decision.Result.SetResult(new(true,.99,"确认完成"));
|
||
for(var i=0;i<10&&engine.CurrentStep?.Id==1;i++)await Emit();
|
||
Counts(1,0,0,0,"A completed step increments only its normal count");
|
||
await Emit();Counts(1,0,0,1,"An abnormally skipped step increments only its abnormal count");
|
||
for(var i=0;i<3;i++)await Emit();Counts(1,0,0,1,"Completed rounds and repeated frames do not duplicate counts");
|
||
engine.Reset();await Task.Delay(30);Counts(1,0,0,1,"Reset preserves per-step totals");
|
||
decision=new UiVisionDecision();engine.VisionDecisionClient=decision;
|
||
for(var i=0;i<10&&!decision.Called.Task.IsCompleted;i++)await Emit();
|
||
engine.Stop();model.IsRunning=false;await Task.Delay(120);
|
||
Counts(1,0,0,1,"Stopping an unfinished step does not count as an abnormal result");
|
||
model.ApplyRecipeCommand.Execute();await Task.Delay(30);Counts(1,0,0,1,"Reapplying a recipe restores the counts on rebuilt cards");
|
||
model.SelectedRecipe="demo.yaml";await Task.Delay(120);Counts(1,0,0,1,"Pending recipe selection does not change the active cards' totals");
|
||
model.ApplyRecipeCommand.Execute();await Task.Delay(120);
|
||
Check(model.StepCards.All(c=>c.NormalCount==0&&c.AbnormalCount==0),"Another recipe has independent step totals");
|
||
model.SelectedRecipe=name+".yaml";model.ApplyRecipeCommand.Execute();await Task.Delay(30);Counts(1,0,0,1,"Returning to the recipe restores its own totals");
|
||
decision=new UiVisionDecision();engine.VisionDecisionClient=decision;engine.Config.Sop.Settings.AutoResetOnComplete=false;
|
||
model.IsRunning=true;engine.Start();
|
||
for(var i=0;i<10&&!decision.Called.Task.IsCompleted;i++)await Emit();
|
||
decision.Result.SetResult(new(true,.99,"确认完成"));
|
||
for(var i=0;i<10&&engine.State!=SopHelper.Engine.Sop.EngineState.Completed;i++)await Emit();
|
||
Counts(2,0,0,2,"Later rounds accumulate each final step result exactly once");
|
||
var countStore=new StepCountsStore(store.Root);
|
||
var savedCounts=countStore.Load(name);
|
||
Check(savedCounts[1].NormalCount==2&&savedCounts[2].AbnormalCount==2,"Each final result is persisted before application exit");
|
||
void AfterRestart(Action<SopPageViewModel> check)
|
||
{
|
||
using var camera=new FakeCamera{Devices=[]};
|
||
using var pipeline=new SopHelper.Engine.Pipeline.DetectionPipeline(camera);
|
||
var fresh=new SopPageViewModel(camera,pipeline,new SopHelper.Engine.Sop.SopEngine(),app.Container.Resolve<IDialogService>());
|
||
try{check(fresh);}finally{fresh.Destroy();}
|
||
}
|
||
AfterRestart(fresh=>Check(fresh.ActiveRecipe==name+".yaml"&&fresh.StepCards[0].NormalCount==2&&fresh.StepCards[1].AbnormalCount==2,
|
||
"A fresh engine and view model restore persisted counts at startup"));
|
||
var view=window.GetVisualDescendants().OfType<SopPage>().Single();
|
||
var texts=view.GetVisualDescendants().OfType<TextBlock>().Select(t=>t.Text).ToArray();
|
||
Check(!texts.Contains("违规 Top3")&&!texts.Contains("完成次数")&&!texts.Contains("平均用时"),"Removed summary and violation panels are absent");
|
||
Check(texts.Count(t=>t?.StartsWith("正常次数:")==true)==2&&texts.Count(t=>t?.StartsWith("异常次数:")==true)==2
|
||
&&texts.Contains("正常次数:2")&&texts.Contains("异常次数:2"),"Every step card renders its bound normal and abnormal counts");
|
||
window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;await Task.Delay(80);window.UpdateLayout();
|
||
var screenshots=Path.GetFullPath(Path.Combine("..","scratch","screenshots"));Directory.CreateDirectory(screenshots);
|
||
using(var rendered=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height)))
|
||
{rendered.Render(window);rendered.Save(Path.Combine(screenshots,"step-result-counts.png"));}
|
||
var resetButton=view.FindControl<Button>("ResetCountsButton")!;
|
||
var buttons=resetButton.GetVisualParent()!.GetVisualChildren().OfType<Button>().ToList();
|
||
Check(buttons.Contains(resetButton)&&!buttons.Any(b=>b.Content?.ToString() is "暂停" or "重置步骤"),
|
||
"Reset counts remains available without the removed run controls");
|
||
countStore.Save("其他配方",new Dictionary<int,SopHelper.Engine.Sop.StepRunCounts>{{1,new(7,4)}});
|
||
var stateBefore=engine.State;var elapsedBefore=model.StepCards[0].ElapsedText;var imageBefore=model.StepCards[0].CompletionImage;
|
||
model.SelectedRecipe="demo.yaml";await Task.Delay(120);
|
||
resetButton.Command!.Execute(resetButton.CommandParameter);
|
||
Counts(0,0,0,0,"Manual reset clears counts for the applied recipe even with a pending selection");
|
||
Check(engine.State==stateBefore&&model.IsRunning&&model.StepCards[0].ElapsedText==elapsedBefore
|
||
&&ReferenceEquals(model.StepCards[0].CompletionImage,imageBefore),"Resetting counts preserves run state, step times and images");
|
||
Check(countStore.Load("其他配方")[1]==new SopHelper.Engine.Sop.StepRunCounts(7,4),"Manual reset preserves other recipes' persisted counts");
|
||
model.SelectedRecipe=name+".yaml";
|
||
AfterRestart(fresh=>Check(fresh.StepCards.All(c=>c.NormalCount==0&&c.AbnormalCount==0),"Manual reset remains zero after a fresh startup"));
|
||
decision=new UiVisionDecision();engine.VisionDecisionClient=decision;engine.Start();
|
||
for(var i=0;i<10&&!decision.Called.Task.IsCompleted;i++)await Emit();
|
||
decision.Result.SetResult(new(true,.99,"确认完成"));
|
||
for(var i=0;i<10&&engine.State!=SopHelper.Engine.Sop.EngineState.Completed;i++)await Emit();
|
||
Counts(1,0,0,1,"New results accumulate normally after manual reset");
|
||
Directory.CreateDirectory(countStore.FilePath+".tmp");
|
||
try
|
||
{
|
||
model.ResetCountsCommand.Execute();
|
||
Counts(1,0,0,1,"A failed reset write preserves the in-memory counts");
|
||
Check(countStore.Load(name)[1].NormalCount==1&&model.StatusText.Contains("重置计数失败"),"A failed reset preserves stored counts and reports the error");
|
||
}
|
||
finally{Directory.Delete(countStore.FilePath+".tmp");}
|
||
engine.Stop();model.IsRunning=false;
|
||
|
||
// 模拟工位上次中断写入后的损坏文件,检查启动、切换配方与后续落盘。
|
||
const string invalidCounts = "{";
|
||
File.WriteAllText(countStore.FilePath, invalidCounts);
|
||
AfterRestart(fresh =>
|
||
{
|
||
Check(fresh.ActiveRecipe == name + ".yaml" && fresh.StepCards.Count == 2
|
||
&& fresh.StepCards.All(card => card.NormalCount == 0 && card.AbnormalCount == 0),
|
||
"损坏的累计次数文件不会阻止启动应用配方");
|
||
fresh.SelectedRecipe = "demo.yaml";
|
||
fresh.ApplyRecipeCommand.Execute();
|
||
Check(fresh.ActiveRecipe == "demo.yaml", "存在损坏文件时仍可切换配方");
|
||
});
|
||
Check(File.ReadAllText(countStore.FilePath) == invalidCounts, "读取失败后保留原统计文件");
|
||
countStore.Save(name, new Dictionary<int,SopHelper.Engine.Sop.StepRunCounts>{{1,new(1,0)}});
|
||
var archived = Directory.GetFiles(Path.GetDirectoryName(countStore.FilePath)!, "step-counts.json.corrupt-*").Single();
|
||
Check(File.ReadAllText(archived) == invalidCounts && countStore.Load(name)[1].NormalCount == 1,
|
||
"首次写入时归档损坏文件并恢复计数持久化");
|
||
}
|
||
|
||
private static async Task CheckRuntimeStatistics(App app,SopPageViewModel sop,Window window)
|
||
{
|
||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||
var name=Path.GetFileNameWithoutExtension(sop.SelectedRecipe)!;
|
||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
SopStandardVideoDuration.Remember(store.DirectoryFor(name),TimeSpan.FromSeconds(3.25));
|
||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;config.Sop.Settings.AutoResetOnComplete=false;
|
||
for(var id=1;id<=2;id++)config.Sop.Steps.Add(new(){Id=id,Name="计时步骤"+id,SaveCompletionImage=false,Detection=new(){Method="object_present",TargetObject="part",StableFrames=1}});
|
||
engine.Load(config);sop.StepCards.Clear();foreach(var step in config.Sop.Steps)sop.StepCards.Add(new(){StepId=step.Id,Name=step.Name,SaveCompletionImage=false});
|
||
var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
|
||
sop.IsRunning=true;engine.Start();
|
||
async Task Emit()
|
||
{
|
||
using(var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90)))
|
||
receive.Invoke(sop,[new SopHelper.Engine.Common.FrameResult {Size=(64,48),Detections=[new(){Label="part",Confidence=1}]},frame]);
|
||
await Task.Delay(40);
|
||
}
|
||
try
|
||
{
|
||
await Task.Delay(1150);
|
||
Check(sop.FlowElapsedText!="00:00:00"&&sop.StepElapsedText!="00:00:00","Flow and step displays advance live without requiring a completion");
|
||
engine.TogglePause();await Task.Delay(120);var paused=sop.FlowElapsedText;await Task.Delay(150);
|
||
Check(sop.FlowElapsedText==paused,"Runtime timer display remains frozen during pause");engine.TogglePause();
|
||
for(var round=1;round<=11;round++)
|
||
{
|
||
if(round>1)engine.Reset();
|
||
await Task.Delay(120);await Emit();await Task.Delay(120);await Emit();await Task.Delay(110);
|
||
Check(sop.CompletedCount==round,"Runtime count updates once after a complete flow");
|
||
Check(sop.AverageDurationText==SopPageViewModel.FormatDuration(engine.Statistics.AverageDuration),"Average display starts only after the eleventh completion");
|
||
}
|
||
Check(sop.StandardDurationText=="00:00:03","Runtime displays the remembered standard SOP video duration");
|
||
Check(sop.StepCards.All(c=>System.Text.RegularExpressions.Regex.IsMatch(c.ElapsedText,@"^\d{2,}:\d{2}:\d{2}$")),"Completed step cards display elapsed times to whole seconds");
|
||
var panel=window.GetVisualDescendants().OfType<Grid>().Single(c=>c.Name=="RunStatisticsPanel");
|
||
var texts=panel.GetVisualDescendants().OfType<TextBlock>().Select(t=>t.Text).ToArray();
|
||
Check(texts.Contains("流程计时")&&!texts.Contains("步骤计时")&&texts.Contains("标准用时")&&!texts.Contains("完成次数")&&!texts.Contains("平均用时"),"Operator page renders timing fields without the removed summary counts");
|
||
Save(window,"runtime-statistics");
|
||
engine.Reset();await Task.Delay(120);
|
||
Check(sop.CompletedCount==11&&sop.StepCards.All(c=>c.ElapsedText=="00:00:00"||c.StepId==1),"Reset begins new step timing while preserving completed count and history");
|
||
}
|
||
finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
|
||
}
|
||
|
||
private static async Task CheckCameraLifecycle(App app,Window window)
|
||
{
|
||
var uvc=new FakeCamera();
|
||
var service=new CameraService(uvc);
|
||
var camera=new CameraInfo {Index=0,UseCompatibilityBackend=true};
|
||
var mode=new UvcCaptureOptions {Width=1280,Height=720,Fps=30};
|
||
await service.ConnectAsync(camera);await service.ConfigureUvcAsync(mode);await service.StartAsync();service.Stop();
|
||
Check(service.IsConnected&&!service.IsGrabbing&&uvc.DisconnectCount==0,"Stop preserves the physical camera connection");
|
||
await service.ConnectAsync(new CameraInfo {Index=0,Name="刷新后的同一相机",UseCompatibilityBackend=true});
|
||
await service.ConfigureUvcAsync(mode with {});await service.StartAsync();
|
||
Check(uvc.ConnectCount==1&&uvc.ConfigureCount==1&&service.IsGrabbing,"Resume reuses the device and skips unchanged video parameters");
|
||
service.Stop();await service.ConfigureUvcAsync(mode with {Fps=15});
|
||
Check(uvc.ConnectCount==1&&uvc.ConfigureCount==2,"Changed camera parameters are applied to the retained connection");
|
||
await service.ConnectAsync(new CameraInfo {Index=1,UseCompatibilityBackend=true});
|
||
await service.ConfigureUvcAsync(mode);
|
||
Check(uvc.DisconnectCount==1&&uvc.ConnectCount==2&&uvc.ConfigureCount==3,"Switching USB cameras releases the previous device and invalidates mode cache");
|
||
var unsupported=false;
|
||
try { await service.ConnectAsync(new CameraInfo {Kind=(CameraKind)1,Index=9}); }
|
||
catch(ArgumentException) { unsupported=true; }
|
||
Check(unsupported&&uvc.ConnectCount==2&&uvc.IsConnected,"Retired camera kinds cannot open or replace the USB connection");
|
||
service.Disconnect();var released=uvc.DisconnectCount;
|
||
await service.ConnectAsync(new CameraInfo {Index=1});
|
||
Check(uvc.DisconnectCount==released&&uvc.ConnectCount==3,"Reconnecting an explicitly released USB device does not release it a second time");
|
||
service.Dispose();service.Dispose();
|
||
Check(uvc.DisposeCount==1&&!uvc.IsConnected,"Exit disposes the USB camera service once");
|
||
var rejected=false;try{await service.ConnectAsync(camera);}catch(ObjectDisposedException){rejected=true;}
|
||
Check(rejected,"Disposed services cannot reopen a camera");
|
||
|
||
var sop=app.Container.Resolve<SopPageViewModel>();
|
||
var workspace=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
const string name="相机生命周期";var path=workspace.ConfigPath(name);
|
||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
|
||
config.Sop.Steps.Add(new(){Id=1,Name="等待",Detection=new(){Method="time_elapsed",DurationMs=600000,StableFrames=1}});
|
||
SopHelper.Engine.Sop.SopConfigLoader.Save(config,path);
|
||
sop.Recipes.Add(name+".yaml");sop.SelectedRecipe=name+".yaml";
|
||
sop.StartStopCommand.Execute();
|
||
for(var i=0;i<250&&!sop.IsRunning;i++)await Task.Delay(20);
|
||
Check(sop.IsRunning&&Camera.IsGrabbing,"Main page starts acquisition");
|
||
var disconnects=Camera.DisconnectCount;
|
||
sop.StartStopCommand.Execute();
|
||
for(var i=0;i<250&&(sop.IsRunning||!sop.CanSelectCamera);i++)await Task.Delay(20);
|
||
Check(!sop.IsRunning&&sop.IsConnected&&Camera.IsConnected&&!Camera.IsGrabbing&&Camera.DisconnectCount==disconnects,
|
||
"Main-page stop leaves an idle connected camera");
|
||
Check(sop.ConfigureCameraCommand.CanExecute()&&sop.EditRecipeCommand.CanExecute()&&sop.DeleteRecipeCommand.CanExecute(),
|
||
"Idle retained connections do not block configuration or recipe editing");
|
||
sop.RefreshCamerasCommand.Execute();
|
||
for(var i=0;i<250&&!sop.CanSelectCamera;i++)await Task.Delay(20);
|
||
Check(Camera.DisconnectCount==disconnects,"Refreshing the list preserves the selected device connection");
|
||
var other=new CameraInfo {Index=1,Name="第二台测试相机"};Camera.Devices.Add(other);sop.SelectedCamera=other;
|
||
for(var i=0;i<250&&(!sop.CanSelectCamera||Camera.IsConnected);i++)await Task.Delay(20);
|
||
Check(!Camera.IsConnected&&Camera.DisconnectCount==disconnects+1,"Changing selection releases the old camera immediately before another start");
|
||
sop.StartStopCommand.Execute();for(var i=0;i<250&&!sop.IsRunning;i++)await Task.Delay(20);
|
||
Check(sop.IsRunning,"The newly selected camera starts successfully");
|
||
sop.StartStopCommand.Execute();for(var i=0;i<250&&(sop.IsRunning||!sop.CanSelectCamera);i++)await Task.Delay(20);
|
||
Check(Camera.IsConnected&&!Camera.IsGrabbing,"The new device is retained after stopping");
|
||
Check(!window.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Name=="InferenceBackend")&&
|
||
sop.Logs.Any(l=>l.Message.Contains("推理设备:")&&l.Message.Contains("步骤确认=")),"Diagnostic details remain in logs only");
|
||
}
|
||
|
||
private static async Task CheckUsbCapture(App app)
|
||
{
|
||
foreach(var invalid in new UvcCaptureOptions[] {new(){Width=1920},new(){Width=0,Height=1080},new(){Fps=double.NaN},new(){Fps=-1},new(){Format="bad"},new(){AutoExposure=false,ExposureTimeMs=0},new(){AutoExposure=true,ExposureTimeMs=10}})
|
||
{
|
||
var rejected=false;try{invalid.Validate();}catch(ArgumentException){rejected=true;}
|
||
Check(rejected,"Invalid USB capture request is rejected before reaching the driver");
|
||
}
|
||
var retired=JsonSerializer.Deserialize<UvcCaptureOptions>("{\"Backend\":1,\"ExposureCompensationEv\":-1,\"LowLightCompensation\":false}")!;
|
||
Check(retired.IsDefault,"Retired backend and compensation settings are safely ignored");
|
||
var controls=new Dictionary<VideoCaptureProperties,double>{{VideoCaptureProperties.Exposure,-3},{VideoCaptureProperties.Mode,1},{VideoCaptureProperties.AutoExposure,3}};
|
||
var writes=new List<(VideoCaptureProperties,double)>();
|
||
double Get(VideoCaptureProperties property)=>controls.GetValueOrDefault(property);
|
||
bool Set(VideoCaptureProperties property,double value){writes.Add((property,value));controls[property]=value;return true;}
|
||
UvcExposureControl.TryApply(new(){AutoExposure=false},VideoCaptureAPIs.MSMF,Get,Set);
|
||
Check(writes.SequenceEqual(new[]{(VideoCaptureProperties.Exposure,-3d)}),"Disabling MSMF auto exposure preserves current time instead of resetting it to one second");
|
||
writes.Clear();
|
||
var windows=UvcExposureControl.TryApply(new(){AutoExposure=false,ExposureTimeMs=15.625},VideoCaptureAPIs.MSMF,Get,Set);
|
||
Check(controls[VideoCaptureProperties.Exposure]==-6&&windows.Contains("15.625"),"Windows manual milliseconds map to logarithmic camera units and read back correctly");
|
||
UvcExposureControl.TryApply(new(){AutoExposure=true},VideoCaptureAPIs.MSMF,Get,Set);
|
||
Check(writes.Last()==(VideoCaptureProperties.AutoExposure,-6d),"Enabling MSMF automatic exposure uses a nonzero value with the auto flag");
|
||
writes.Clear();
|
||
UvcExposureControl.TryApply(new(){AutoExposure=true},VideoCaptureAPIs.DSHOW,Get,Set);
|
||
Check(writes.Last()==(VideoCaptureProperties.AutoExposure,1d),"Windows compatibility capture uses its own automatic-exposure flag encoding");
|
||
UvcExposureControl.TryApply(new(){AutoExposure=false,ExposureTimeMs=15.625},VideoCaptureAPIs.DSHOW,Get,Set);
|
||
Check(controls[VideoCaptureProperties.Exposure]==-6,"Windows compatibility capture also supports unified manual milliseconds");
|
||
writes.Clear();
|
||
var linux=UvcExposureControl.TryApply(new(){AutoExposure=false,ExposureTimeMs=15.6},VideoCaptureAPIs.V4L2,Get,Set);
|
||
Check(controls[VideoCaptureProperties.AutoExposure]==1&&controls[VideoCaptureProperties.Exposure]==156&&controls[VideoCaptureProperties.Mode]==1&&linux.Contains("15.6"),
|
||
"Linux exposure uses raw 100-microsecond units and restores OpenCV normalization");
|
||
bool LinuxAutoSet(VideoCaptureProperties property,double value)=>property==VideoCaptureProperties.AutoExposure&&value==0 ? false : Set(property,value);
|
||
Check(UvcExposureControl.TryApply(new(){AutoExposure=true},VideoCaptureAPIs.V4L2,Get,LinuxAutoSet).Contains("自动")&&controls[VideoCaptureProperties.AutoExposure]==3,
|
||
"Linux auto exposure falls back to aperture-priority mode for UVC drivers");
|
||
Check(UvcExposureControl.TryApply(new(){AutoExposure=false},VideoCaptureAPIs.MSMF,Get,(_,_)=>false)==""&&
|
||
UvcExposureControl.TryApply(new(){AutoExposure=false},VideoCaptureAPIs.V4L2,_=>throw new NotSupportedException(),Set)=="",
|
||
"Unsupported exposure controls silently skip without throwing");
|
||
var lifetime=(IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!;
|
||
var sop=app.Container.Resolve<SopPageViewModel>();
|
||
app.Container.Resolve<NavigationModel>().SelectedIndex=1;await Task.Delay(120);
|
||
var button=lifetime.MainWindow!.GetVisualDescendants().OfType<Button>().Single(b=>b.Name=="ConfigureCameraButton");
|
||
button.Command!.Execute(button.CommandParameter);await Task.Delay(80);
|
||
var dialog=lifetime.Windows.OfType<SopHelper.VVMs.CameraSettings.CameraSettingsWindow>().Single();
|
||
try
|
||
{
|
||
Check(dialog.FindControl<Button>("DriverPropertiesButton") is null&&dialog.FindControl<ComboBox>("CaptureBackendPicker") is null
|
||
&&dialog.FindControl<TextBox>("ExposureInput") is null,
|
||
"Camera configuration contains only USB controls without industrial exposure or backend selection");
|
||
dialog.FindControl<ComboBox>("ResolutionPicker")!.SelectedItem=dialog.Model.Resolutions.Single(r=>r.Width==1920&&r.Height==1080);
|
||
dialog.FindControl<ComboBox>("FrameRatePicker")!.SelectedItem=dialog.Model.FrameRates.Single(r=>r.Fps==30);
|
||
dialog.FindControl<ComboBox>("FormatPicker")!.SelectedItem="MJPG";
|
||
var mode=dialog.FindControl<ComboBox>("AutoExposurePicker")!;
|
||
var exposure=dialog.FindControl<NumericUpDown>("UsbExposureInput")!;
|
||
Check(!exposure.IsEffectivelyEnabled,"Manual exposure time is disabled until automatic exposure is turned off");
|
||
mode.SelectedItem=dialog.Model.ExposureModes.Single(m=>m.Enabled==false);await Task.Delay(20);
|
||
Check(exposure.IsEffectivelyEnabled,"Turning off auto exposure enables manual milliseconds input");
|
||
exposure.Value=15.625m;await Task.Delay(20);Save(dialog,"camera-settings");
|
||
dialog.FindControl<Button>("SaveCameraSettingsButton")!.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));await Task.Delay(80);
|
||
var store=CameraSettingsStore.Current;
|
||
Check(store.Load(sop.SelectedCamera!).UsbCapture is {Width:1920,Height:1080,Fps:30,Format:"MJPG",AutoExposure:false,ExposureTimeMs:15.625},
|
||
"Unified auto/manual exposure and video settings are saved per camera");
|
||
var reopened=new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(sop.SelectedCamera!,store);
|
||
Check(reopened.IsManualExposure&&reopened.UsbExposureTimeMs==15.625m,"Manual exposure is restored when reopening configuration");
|
||
var saved=File.ReadAllText(store.FilePath);
|
||
Check(!saved.Contains("Backend")&&!saved.Contains("ExposureCompensationEv")&&!saved.Contains("LowLightCompensation"),"Saved settings exclude removed Windows-specific controls");
|
||
using var probe=new FakeCamera();await store.ConnectAsync(probe,sop.SelectedCamera!);await store.ApplyAsync(probe,sop.SelectedCamera!);
|
||
Check(probe.LastUsbOptions is {AutoExposure:false,ExposureTimeMs:15.625},"Acquisition receives the saved platform-independent exposure settings");
|
||
reopened.SelectedAutoExposure=reopened.ExposureModes.Single(m=>m.Enabled==true);Check(reopened.Save()&&store.Load(sop.SelectedCamera!).UsbCapture is {AutoExposure:true,ExposureTimeMs:null},
|
||
"Enabling auto exposure clears the manual-time request");
|
||
Check(store.Load(new CameraInfo{Index=9}).UsbCapture.IsDefault,"Other cameras preserve their independent defaults");
|
||
}
|
||
finally {dialog.Close();}
|
||
}
|
||
|
||
private static async Task CheckCompletionImageSaving(App app,SopPageViewModel sop)
|
||
{
|
||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
var name="结束图测试";var file=name+".yaml";
|
||
var selected=sop.SelectedRecipe;
|
||
var archiveRoot=Path.Combine(store.DirectoryFor(name),"completion-images");
|
||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
|
||
config.Sop.Settings.AutoResetOnComplete=false;config.Sop.Settings.StableFrames=1;
|
||
for(var id=1;id<=4;id++)
|
||
{
|
||
config.Sop.Regions["工位"+id]=new(){X1=(id-1)*16,Y1=0,X2=id*16,Y2=48};
|
||
config.Sop.Steps.Add(new()
|
||
{
|
||
Id=id,Name=id==1?"装配/检查":id==4?"装配_检查":"步骤"+id,SaveCompletionImage=id!=2,
|
||
Description="零件安装到位",
|
||
Detection=new(){Method="hand_in_region",Region="工位"+id,StableFrames=1,Tolerance=0},
|
||
AiConfirmation=new(){ImageMode="full_frame",EvidenceMode="single_frame",CheckWindowMs=0}
|
||
});
|
||
}
|
||
var legacy=SopConfigLoader.Parse("sop:\n name: legacy\n steps:\n - id: 1\n name: first\n completion_image_directory: old-images\n");
|
||
Check(legacy.Sop.Steps[0].SaveCompletionImage&&!SopConfigLoader.ToYaml(legacy).Contains("completion_image_directory"),
|
||
"旧配方保留默认保存开关,旧目录配置在重新保存时清理");
|
||
var node=RecipeNode.From(config,file,false);
|
||
var roundTrip=SopHelper.Engine.Sop.SopConfigLoader.Parse(SopHelper.Engine.Sop.SopConfigLoader.ToYaml(node.ToConfig()));
|
||
Check(roundTrip.Sop.Steps[0].SaveCompletionImage&&!roundTrip.Sop.Steps[1].SaveCompletionImage,"步骤编辑和 YAML 往返保留结束图开关");
|
||
Directory.CreateDirectory(store.DirectoryFor(name));
|
||
SopHelper.Engine.Sop.SopConfigLoader.Save(roundTrip,store.ConfigPath(name));
|
||
var editorVm=new RecipeEditorViewModel();
|
||
editorVm.OnDialogOpened(new DialogParameters{{"directory",store.RecipesDirectory},{"path",store.ConfigPath(name)},{"config",roundTrip},{"new",false}});
|
||
var editor=new RecipeEditor{DataContext=editorVm};
|
||
var dialog=new Window{Content=editor,Width=1040,Height=760};dialog.Show();await Task.Delay(60);
|
||
try
|
||
{
|
||
editor.FindControl<Expander>("StepAdditionalSettings")!.IsExpanded=true;await Task.Delay(20);
|
||
var toggle=editor.GetVisualDescendants().OfType<CheckBox>().Single(c=>c.Content?.ToString()=="保存结束图");
|
||
Check(toggle.IsChecked==true&&editor.FindControl<TextBox>("CompletionImageDirectoryBox") is null
|
||
&& !editor.GetVisualDescendants().OfType<Button>().Any(button=>button.Content?.ToString() is "选择目录…" or "恢复默认"),
|
||
"结束图设置仅保留保存开关");
|
||
toggle.IsChecked=false;await Task.Delay(20);
|
||
Check(!editorVm.Recipe.SelectedStep!.SaveCompletionImage,"关闭结束图开关更新当前步骤");
|
||
toggle.IsChecked=true;editorVm.SaveCommand.Execute();await Task.Delay(20);
|
||
var saved=SopHelper.Engine.Sop.SopConfigLoader.Load(store.ConfigPath(name));
|
||
Check(saved.Sop.Steps[0].SaveCompletionImage&&!saved.Sop.Steps[1].SaveCompletionImage,"编辑器保存每步的结束图开关");
|
||
editorVm.Recipe.SelectedStep=editorVm.Recipe.Steps[0];await Task.Delay(20);Save(dialog,"step-completion-image-settings");
|
||
}
|
||
finally{await editorVm.ShutdownAsync();dialog.Close();}
|
||
sop.Recipes.Add(file);sop.SelectedRecipe=file;sop.ApplyRecipeCommand.Execute();
|
||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||
var previousClient=engine.VisionDecisionClient;
|
||
var decision=new UiVisionDecision();
|
||
decision.Result.SetResult(new(true,.99,"确认完成"));
|
||
engine.VisionDecisionClient=decision;
|
||
var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
|
||
var frameId=0;
|
||
async Task WaitForImages()
|
||
{
|
||
await (Task)typeof(SopPageViewModel).GetField("_completionImageSaves",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!.GetValue(sop)!;
|
||
await Task.Delay(30);
|
||
}
|
||
async Task Round()
|
||
{
|
||
for(var id=1;id<=4;id++)
|
||
{
|
||
// 每步使用独立触发区域和颜色,经真实引擎取图,再用后续帧收取模拟 AI 结果。
|
||
using(var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(id*30,60,90)))
|
||
{
|
||
for(var attempt=0;attempt<20&&engine.CurrentStep?.Id==id;attempt++)
|
||
{
|
||
receive.Invoke(sop,[new SopHelper.Engine.Common.FrameResult{FrameId=++frameId,Timestamp=DateTime.Now,Size=(64,48),
|
||
Hands=[new(){Rect=new((id-1)*16+3,20,10,10)}]},frame]);
|
||
await Task.Delay(15);
|
||
}
|
||
}
|
||
Check(sop.StepCards[id-1].HasCompletionImage,$"步骤 {id} 通过后生成完成图");
|
||
}
|
||
await WaitForImages();
|
||
}
|
||
try
|
||
{
|
||
engine.Config.Sop.Settings.AutoResetOnComplete=true;
|
||
engine.Config.Sop.Settings.ResetDelaySec=1;
|
||
sop.IsRunning=true;engine.Start();
|
||
// 第一帧之前就应有空目录,待应用的配方不能改变本轮路径。
|
||
var first=Directory.GetDirectories(archiveRoot).Single();
|
||
Check(DateTime.TryParseExact(Path.GetFileName(first),"yyyy-MM-dd_HH-mm-ss'-0'",System.Globalization.CultureInfo.InvariantCulture,
|
||
System.Globalization.DateTimeStyles.None,out _)&&Directory.GetFiles(first).Length==0,"开始检测时即创建序号为 0 的日期时间目录");
|
||
sop.SelectedRecipe=selected;
|
||
await Round();
|
||
var expected=new Dictionary<string,byte>{{"装配_检查.png",30},{"步骤3.png",90},{"装配_检查-2.png",120}};
|
||
void CheckRoundImages(string directory)
|
||
{
|
||
Check(Directory.GetFiles(directory,"*.png").Length==expected.Count,"同轮只保存开启归档的步骤");
|
||
foreach(var (imageName,blue) in expected)
|
||
{
|
||
using var image=Cv2.ImDecode(File.ReadAllBytes(Path.Combine(directory,imageName)),ImreadModes.Color);
|
||
Check(image.Width==64&&image.Height==48&&Math.Abs(image.At<Vec3b>(0,0).Item0-blue)<=3,$"{imageName} 对应原判定帧");
|
||
}
|
||
}
|
||
CheckRoundImages(first);
|
||
Check(sop.StepCards[1].HasCompletionImage,"关闭保存的步骤仍显示完成图片");
|
||
for(var attempt=0;attempt<100&&Directory.GetDirectories(archiveRoot).Length==1;attempt++)await Task.Delay(20);
|
||
var second=Directory.GetDirectories(archiveRoot).Single(path=>path!=first);
|
||
Check(Directory.GetFiles(second).Length==0&&engine.State==EngineState.Running,"自动复位在新一轮首帧之前创建空目录");
|
||
engine.Config.Sop.Settings.AutoResetOnComplete=false;
|
||
await Round();
|
||
CheckRoundImages(first);
|
||
CheckRoundImages(second);
|
||
|
||
// 用同名文件阻挡新配方创建归档根目录,确认检测仍可完成。
|
||
sop.IsRunning=false;
|
||
var blockedName=name+"失败";
|
||
var blockedFile=blockedName+".yaml";
|
||
roundTrip.Sop.Name=blockedName;
|
||
Directory.CreateDirectory(store.DirectoryFor(blockedName));
|
||
SopConfigLoader.Save(roundTrip,store.ConfigPath(blockedName));
|
||
File.WriteAllText(Path.Combine(store.DirectoryFor(blockedName),"completion-images"),"blocked");
|
||
sop.Recipes.Add(blockedFile);
|
||
try
|
||
{
|
||
sop.SelectedRecipe=blockedFile;sop.ApplyRecipeCommand.Execute();
|
||
engine.Config.Sop.Settings.AutoResetOnComplete=false;
|
||
sop.IsRunning=true;engine.Start();
|
||
await Round();
|
||
Check(engine.State==EngineState.Completed&&sop.Logs.Any(l=>l.Message.Contains("本轮结束图目录创建失败")),"归档目录创建失败有日志,检测继续完成");
|
||
CheckRoundImages(second);
|
||
Check(Directory.GetDirectories(archiveRoot).Length==2,"创建失败的轮次不会写入上一轮目录");
|
||
}
|
||
finally { sop.Recipes.Remove(blockedFile); }
|
||
}
|
||
finally
|
||
{
|
||
await WaitForImages();sop.IsRunning=false;engine.VisionDecisionClient=previousClient;
|
||
sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
|
||
sop.Recipes.Remove(file);
|
||
}
|
||
}
|
||
|
||
/// <summary>验证新增步骤命令的插入位置、选中项以及保存后的执行顺序。</summary>
|
||
private static void CheckAddStep()
|
||
{
|
||
var insertion = new RecipeNode();
|
||
var first = insertion.AddStep();
|
||
var second = insertion.AddStep();
|
||
first.Name = "第一步";
|
||
second.Name = "第二步";
|
||
insertion.AddStepCommand.Execute();
|
||
var inserted = insertion.SelectedStep;
|
||
Check(inserted is not null && insertion.Steps.SequenceEqual(new[] { first, inserted, second })
|
||
&& insertion.ToConfig().Sop.Steps.Select(step => step.Name).SequenceEqual(new[] { "第一步", "新步骤", "第二步" }),
|
||
"Adding with a selected step inserts and saves the new step immediately above it");
|
||
insertion.SelectedStep = null;
|
||
insertion.AddStepCommand.Execute();
|
||
Check(insertion.Steps.Count == 4 && insertion.Steps[^2] == second
|
||
&& insertion.Steps[^1] == insertion.SelectedStep && insertion.Steps[^1].Id == 4,
|
||
"Adding without a selection appends and selects the new step");
|
||
}
|
||
|
||
private static async Task CheckVisionConfirmation(App app,SopPageViewModel sop)
|
||
{
|
||
CheckAddStep();
|
||
var numbering=new RecipeNode();
|
||
var numbered=new[]{numbering.AddStep(),numbering.AddStep(),numbering.AddStep(),numbering.AddStep()};
|
||
for(var i=0;i<numbered.Length;i++)numbered[i].Name="step-"+(i+1);
|
||
numbering.MoveStepDown(numbered[1]);numbering.RemoveStep(numbered[2]);
|
||
Check(numbering.Steps.Select(step=>step.Id).SequenceEqual(new[]{1,2,3})
|
||
&&numbering.ToConfig().Sop.Steps.Select(step=>step.Name).SequenceEqual(new[]{"step-1","step-2","step-4"}),
|
||
"Deleting a reordered middle step closes numbering gaps and preserves saved step order");
|
||
Check(numbering.AddStep().Id==4,"Adding after deletion continues the updated numbering");
|
||
numbering.RemoveStep(numbering.Steps[0]);numbering.RemoveStep(numbering.Steps[^1]);
|
||
Check(numbering.Steps.Select(step=>step.Id).SequenceEqual(new[]{1,2}),"Deleting first and last steps keeps numbering continuous");
|
||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||
var name="手部AI验证";var file=name+".yaml";
|
||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
|
||
config.Sop.Settings.AutoResetOnComplete=false;
|
||
config.Sop.Regions["work"]=new(){X1=0,Y1=0,X2=64,Y2=48};
|
||
config.Sop.Steps.Add(new(){Id=1,Name="装配",Description="红色零件安装到位",Detection=new(){Method="hand_in_region",Region="work",StableFrames=1},
|
||
AiConfirmation=new(){ImageRegion="work",MinConfidence=.9,RetryDelayMs=4500,TimeoutSeconds=20}});
|
||
var roundTrip=RecipeNode.From(config,file,false).ToConfig();
|
||
var ai=roundTrip.Sop.Steps[0].AiConfirmation;
|
||
Check(ai is {ImageRegion:"work",MinConfidence:.9,RetryDelayMs:4500,TimeoutSeconds:20} && roundTrip.Sop.Steps[0].Description=="红色零件安装到位","AI settings and step description survive editor mapping");
|
||
Directory.CreateDirectory(store.DirectoryFor(name));SopHelper.Engine.Sop.SopConfigLoader.Save(roundTrip,store.ConfigPath(name));
|
||
var editorVm=new RecipeEditorViewModel();
|
||
editorVm.OnDialogOpened(new DialogParameters{{"directory",store.RecipesDirectory},{"path",store.ConfigPath(name)},{"config",roundTrip},{"new",false}});
|
||
var editor=new RecipeEditor{DataContext=editorVm};
|
||
var dialog=new Window{Content=editor,Width=1040,Height=900};dialog.Show();await Task.Delay(80);
|
||
try
|
||
{
|
||
if(Environment.GetCommandLineArgs().Contains("--agent-only"))
|
||
{ await CheckVideoAgent(editorVm,editor,dialog,store); return; }
|
||
Check(!editor.GetVisualDescendants().OfType<CheckBox>().Any(c=>c.Content?.ToString()=="手部动作触发后由 AI 确认完成"),"AI confirmation no longer has an opt-out checkbox");
|
||
var headers=editor.GetVisualDescendants().OfType<TabItem>().Select(t=>t.Header?.ToString()).ToArray();
|
||
// 区域已并入步骤页,运行参数由运行设置窗口管理。
|
||
Check(headers.SequenceEqual(new[]{"步骤","SOP流程视频","Agent助手"}),"配方编辑器保留步骤、标准视频和 Agent 三个标签页");
|
||
Check(editor.FindControl<ComboBox>("TargetPartPicker") is null,"Step editor removes YOLO target-class picker");
|
||
Check(editorVm.Recipe.Methods.All(m=>!m.StartsWith("object_")&&m!="hand_near_object"),"Only hand and timer trigger methods are offered");
|
||
Check(editor.FindControl<TextBox>("CameraExposureInput") is null,"Camera exposure is configured separately from recipes");
|
||
var picker=editor.FindControl<ComboBox>("AiImageRegionPicker")!;
|
||
var modePicker=editor.FindControl<ComboBox>("AiImageModePicker")!;
|
||
Check(modePicker.SelectedItem?.ToString()=="fixed_region","Legacy crop settings select fixed-region mode");
|
||
Check(picker.SelectedItem?.ToString()=="work","Editor exposes configured image region");
|
||
modePicker.SelectedItem="full_frame";await Task.Delay(20);
|
||
Check(editorVm.Recipe.ToConfig().Sop.Steps[0].AiConfirmation?.ImageMode=="full_frame"&&!picker.IsEffectivelyVisible,"Editor switches to full frame and hides fixed region");
|
||
modePicker.SelectedItem="hand";await Task.Delay(20);
|
||
var padding=editor.FindControl<NumericUpDown>("AiHandPaddingInput")!;
|
||
Check(padding.IsEffectivelyVisible,"Hand-follow mode exposes crop range controls");
|
||
// 送检手别在计时触发时也能编辑,并通过配方保存与加载往返。
|
||
var handPicker=editor.FindControl<ComboBox>("AiImageHandPicker")!;
|
||
var trigger=editor.FindControl<ComboBox>("StepTriggerMethodPicker")!;
|
||
var originalTrigger=trigger.SelectedItem;
|
||
var triggerHand=editorVm.Recipe.ToConfig().Sop.Steps[0].Detection?.Hand;
|
||
trigger.SelectedItem=ConditionMethod.TimeElapsed;await Task.Delay(20);
|
||
Check(handPicker.IsEffectivelyVisible&&Equals(handPicker.SelectedItem,"any"),"计时跟手送检应显示独立手别并默认任何手");
|
||
handPicker.SelectedItem="left";
|
||
trigger.SelectedItem=originalTrigger;
|
||
padding.Value=200;await Task.Delay(20);
|
||
var handConfig=SopConfigLoader.Parse(SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig())).Sop.Steps[0];
|
||
Check(handConfig.AiConfirmation is {ImageMode:"hand",ImageHand:"left",HandPadding:200,HandMinSize:320,HandMemoryMs:3000}
|
||
&&handConfig.Detection?.Hand==triggerHand,"送检手别应单独保存,切换触发方式后仍保留");
|
||
var description=editor.FindControl<TextBox>("StepDescriptionBox")!;
|
||
Check(description.Text=="红色零件安装到位","Step description is the only editable completion condition");
|
||
description.Text="把红色零件放到盒子里";await Task.Delay(20);
|
||
Check(editorVm.Recipe.ToConfig().Sop.Steps[0].Description==description.Text,"Editing original step description updates the AI completion condition");
|
||
var added=editorVm.Recipe.AddStep();
|
||
Check(editorVm.Recipe.ToConfig().Sop.Steps.Last().AiConfirmation is not null && added.Description=="","New steps default to AI confirmation and require a step description");
|
||
editorVm.Recipe.Steps.Remove(added);
|
||
editorVm.Recipe.SelectedStep=editorVm.Recipe.Steps[0];await Task.Delay(20);
|
||
Save(dialog,"hand-ai-confirmation-settings");
|
||
await CheckVideoAgent(editorVm,editor,dialog,store);
|
||
}
|
||
finally{await editorVm.ShutdownAsync();dialog.Close();}
|
||
var settingsView=new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(sop);
|
||
var settingsWindow=new Window{Content=settingsView,Width=900,Height=720};settingsWindow.Show();await Task.Delay(40);
|
||
try
|
||
{
|
||
// 自动登录也有下拉框,按无障碍名称确认相机和配方入口。
|
||
var pickerNames = settingsView.GetVisualDescendants().OfType<ComboBox>()
|
||
.Select(Avalonia.Automation.AutomationProperties.GetName).ToArray();
|
||
var sliders = settingsView.GetVisualDescendants().OfType<Slider>().ToArray();
|
||
Check(pickerNames.Contains("相机") && pickerNames.Contains("配方")
|
||
&& sliders.Length == 1 && sliders[0].Minimum == 1 && sliders[0].Maximum == 10,
|
||
"运行设置保留相机、配方和抽帧入口,且没有旧阈值滑杆");
|
||
Check(settingsView.GetVisualDescendants().OfType<CheckBox>().Any(c=>c.Content?.ToString()=="完成后自动复位")
|
||
&& settingsView.GetVisualDescendants().OfType<NumericUpDown>().Any(),"运行设置包含自动复位和复位延时");
|
||
sop.FrameStride=3;sop.AutoResetOnComplete=false;sop.ResetDelaySec=4;
|
||
var runtime=RuntimeSettingsStore.Current.Read()!;
|
||
Check(runtime.FrameStride==3&&!runtime.AutoResetOnComplete&&runtime.ResetDelaySec==4,"运行设置修改后独立持久化");
|
||
Save(settingsWindow,"runtime-settings-no-yolo");
|
||
}
|
||
finally{settingsWindow.Close();}
|
||
sop.Recipes.Add(file);sop.SelectedRecipe=file;sop.ApplyRecipeCommand.Execute();
|
||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||
var fake=new UiVisionDecision();engine.VisionDecisionClient=fake;
|
||
var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
|
||
async Task Emit(Scalar color)
|
||
{
|
||
using(var frame=new Mat(48,64,MatType.CV_8UC3,color))
|
||
receive.Invoke(sop,[new SopHelper.Engine.Common.FrameResult{FrameId=7,Timestamp=DateTime.Now,Size=(64,48),Hands=[new(){Rect=new(20,20,10,10)}]},frame]);
|
||
await Task.Delay(40);
|
||
}
|
||
try
|
||
{
|
||
sop.IsRunning=true;engine.Start();
|
||
await Emit(new Scalar(0,0,240));
|
||
await fake.Called.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||
Check(!sop.StepCards[0].HasCompletionImage&&engine.State==SopHelper.Engine.Sop.EngineState.Running,"Hand action alone does not complete a step");
|
||
fake.Result.SetResult(new(true,.98,"红色零件已安装到位"));
|
||
for(int i=0;i<100&&engine.State!=SopHelper.Engine.Sop.EngineState.Completed;i++)await Emit(new Scalar(240,0,0));
|
||
Check(engine.State==SopHelper.Engine.Sop.EngineState.Completed&&sop.StepCards[0].HasCompletionImage,"AI confirmation advances actual runtime UI");
|
||
await (Task)typeof(SopPageViewModel).GetField("_completionImageSaves",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!.GetValue(sop)!;
|
||
var archive=Directory.GetDirectories(Path.Combine(store.DirectoryFor(name),"completion-images")).Single();
|
||
using var evidence=Cv2.ImDecode(File.ReadAllBytes(Path.Combine(archive,"装配.png")),ImreadModes.Color);var pixel=evidence.At<Vec3b>(0,0);
|
||
Check(pixel.Item2>230&&pixel.Item0<10,"Saved image is red AI input, not blue frame at response arrival");
|
||
}
|
||
finally{sop.IsRunning=false;engine.Stop();}
|
||
}
|
||
|
||
private static async Task CheckVideoAgent(RecipeEditorViewModel model,RecipeEditor editor,Window dialog,RecipeWorkspace store)
|
||
{
|
||
var video=Path.Combine(store.Root,"agent-standard.avi");
|
||
using(var writer=new VideoWriter())
|
||
{
|
||
// 视频长边超过模型取样上限,便于区分保存的关键帧和分析缩图。
|
||
Check(writer.Open(video,FourCC.MJPG,10,new OpenCvSharp.Size(800,600)),"Agent test video opens");
|
||
for(var i=0;i<40;i++){using var frame=new Mat(600,800,MatType.CV_8UC3,new Scalar(i*4,60,90));writer.Write(frame);}
|
||
}
|
||
var client=new UiSopAgent();model.AgentClient=client;
|
||
Check(model.AgentContextLength==131702&&model.AgentMaxTokens==8192,"Assistant defaults use the requested context and output lengths");
|
||
Check(model.AgentMaxFrames==3,"Assistant defaults to at most three sampled frames");
|
||
model.AgentVideoPath=video;model.AgentEndpoint="https://custom.invalid/v1/chat/completions";
|
||
model.AgentModel="custom-vision";model.AgentApiKey="remember-test-key";model.AgentMaxFrames=3;
|
||
model.AgentContextLength=16384;model.AgentMaxTokens=2048;model.AgentTemperature=.4;model.AgentTopP=.8;model.AgentTimeoutSeconds=90;
|
||
var settingsPath=Path.Combine(store.Root,"workspace","sop-agent.json");
|
||
Check(File.ReadAllText(settingsPath).Contains("custom-vision"),"Model settings are saved before any analysis request");
|
||
async Task<RecipeEditorViewModel> ReopenAgent()
|
||
{
|
||
var restored=new RecipeEditorViewModel();
|
||
restored.OnDialogOpened(new DialogParameters{{"directory",store.RecipesDirectory},{"new",true}});
|
||
await restored.ShutdownAsync();
|
||
return restored;
|
||
}
|
||
var reopened=await ReopenAgent();
|
||
Check(reopened.AgentEndpoint==model.AgentEndpoint&&reopened.AgentModel==model.AgentModel&&reopened.AgentApiKey==model.AgentApiKey,
|
||
"A fresh editor restores endpoint, model and key without requiring successful analysis");
|
||
Check(reopened.AgentMaxFrames==3&&reopened.AgentContextLength==16384&&reopened.AgentMaxTokens==2048
|
||
&&reopened.AgentTemperature==.4&&reopened.AgentTopP==.8&&reopened.AgentTimeoutSeconds==90,
|
||
"A fresh editor restores sampling, context, output, temperature, top P and timeout settings");
|
||
model.AgentMaxFrames=5;
|
||
Check((await ReopenAgent()).AgentMaxFrames==5,"Custom frame count persists across editor restarts");
|
||
model.AgentMaxFrames=3;
|
||
model.AgentApiKey="";
|
||
Check((await ReopenAgent()).AgentApiKey=="","Clearing the key persists across editor restarts");
|
||
model.AgentApiKey="remember-test-key";
|
||
var originalSteps=model.Recipe.Steps.ToArray();
|
||
var originalCount=model.Recipe.Steps.Count;
|
||
var configPath=store.ConfigPath("手部AI验证");var before=File.ReadAllBytes(configPath);
|
||
var tabs=editor.GetVisualDescendants().OfType<TabControl>().First();tabs.SelectedItem=tabs.Items.OfType<TabItem>().Single(t=>Equals(t.Header,"Agent助手"));await Task.Delay(30);
|
||
editor.FindControl<Expander>("AgentSettingsExpander")!.IsExpanded=true;await Task.Delay(30);
|
||
Check(editor.FindControl<TextBox>("AgentEndpointBox")!.IsEffectivelyVisible,"Assistant exposes configurable endpoint and model fields");
|
||
editor.FindControl<Expander>("AgentSettingsExpander")!.IsExpanded=false;
|
||
model.GenerateStepsCommand.Execute();
|
||
for(var i=0;i<300&&model.IsAgentBusy;i++)await Task.Delay(10);
|
||
Check(!model.IsAgentBusy&&model.AgentDraftSteps.Count==2,"Assistant samples video and presents model-generated draft steps");
|
||
Check(client.Connection?.Endpoint==model.AgentEndpoint&&client.Connection.Model==model.AgentModel&&client.Request?.Video.Frames.Count==0
|
||
&&client.Request.Video.Path==Path.GetFullPath(video)&&client.Request.MaxFramesPerRead==3,
|
||
"Assistant starts with the local video path and per-tool frame limit instead of preselected images");
|
||
Check(client.Connection?.MaxTokens==2048&&client.Connection.ContextLength==16384&&client.Connection.Temperature==.4
|
||
&&client.Connection.TopP==.8&&client.Connection.TimeoutSeconds==90,"Analysis receives the configured generation parameters");
|
||
Check(model.Recipe.Steps.Count==originalCount&&File.ReadAllBytes(configPath).SequenceEqual(before),"Generating a draft does not replace steps or write the recipe");
|
||
Check(client.Request?.RegionDefinitions?["work"].X2==64,"Agent receives the current calibrated region geometry");
|
||
var candidate=model.AgentDraftSteps[0].Step;
|
||
candidate.Method="hand_move";candidate.FromRegion="";candidate.ToRegion="work";
|
||
model.ApplyAgentDraftCommand.Execute();
|
||
Check(model.Recipe.Steps.Count==originalCount&&File.ReadAllBytes(configPath).SequenceEqual(before),
|
||
"Apply rejects a generated move missing its origin without modifying the recipe");
|
||
candidate.Method="hand_leave_region";candidate.ToRegion="";
|
||
Check((await ReopenAgent()).AgentApiKey==model.AgentApiKey,"Successful analysis preserves the saved key");
|
||
model.AgentDraftSteps[0].Description="把连接器放入盒子,盒内可见连接器";
|
||
async Task SendChat(string text)
|
||
{
|
||
model.AgentChatInput=text;model.SendAgentChatCommand.Execute();
|
||
for(var i=0;i<300&&model.IsAgentBusy;i++)await Task.Delay(10);
|
||
}
|
||
await SendChat("第一步改名为放入连接器,说明保持");
|
||
Check(model.AgentDraftSteps[0].Name=="放入连接器"&&model.AgentDraftSteps[0].Description=="把连接器放入盒子,盒内可见连接器",
|
||
"Chat updates draft steps while preserving manual edits");
|
||
Check(client.ChatRequest?.UserMessage=="第一步改名为放入连接器,说明保持"&&client.ChatRequest.CurrentDraft?.Steps[0].Description=="把连接器放入盒子,盒内可见连接器"
|
||
&&client.ChatRequest.Video.Frames.Count==3,"Chat receives current edited draft and observed video frames");
|
||
Check(client.ChatRequest?.ImageScopes?[0] is {Mode:"fixed_region",Region:"work"},"Chat receives the actual fixed image crop for the draft");
|
||
var editedRow=model.AgentDraftSteps[0];
|
||
client.ChatOnly=true;await SendChat("先解释一下,不要改步骤");
|
||
Check(ReferenceEquals(editedRow,model.AgentDraftSteps[0])&&client.ChatRequest?.Conversation?.Any(turn=>turn.Text.Contains("第一步改名"))==true,
|
||
"Discussion keeps the draft and includes previous conversation");
|
||
client.ChatOnly=false;client.InvalidChat=true;await SendChat("修改一下");
|
||
Check(ReferenceEquals(editedRow,model.AgentDraftSteps[0]),"Invalid chat edits leave the current draft untouched");
|
||
client.InvalidChat=false;
|
||
client.ChatOnly=true;await SendChat("先不要改动,解释一下这两个动作");client.ChatOnly=false;
|
||
Check(client.ChatRequest?.Conversation?.All(turn=>turn.Text!="修改一下")==true,"Failed chat requests are not committed to model conversation");
|
||
Check(editor.FindControl<TextBox>("AgentChatInputBox")!.IsEffectivelyVisible&&model.AgentChatMessages.Any(line=>line.Speaker=="Agent"),
|
||
"Assistant exposes chat input and visible agent replies");
|
||
Save(dialog,"sop-video-agent-draft");
|
||
client.Hold=true;
|
||
model.GenerateStepsCommand.Execute();
|
||
for(var i=0;i<200&&!client.Held;i++)await Task.Delay(10);
|
||
Check(model.IsAgentBusy&&client.Held,"Assistant cancellation test reaches pending model request");
|
||
model.CancelAgentCommand.Execute();
|
||
for(var i=0;i<100&&model.IsAgentBusy;i++)await Task.Delay(10);
|
||
Check(!model.IsAgentBusy&&model.Recipe.Steps.Count==originalCount,"Cancelling analysis never mutates the recipe");
|
||
Check(editor.GetVisualDescendants().OfType<Button>().Any(b=>Equals(b.Content,"取消任务")),"Assistant uses the cancel task label");
|
||
async Task ApplyDraft(string buttonName, bool completed)
|
||
{
|
||
model.ApplyAgentDraftCommand.Execute();
|
||
for(var i=0;i<100&&!dialog.OwnedWindows.Any();i++)await Task.Delay(10);
|
||
var choice=dialog.OwnedWindows.Single();
|
||
Check(choice.Title=="更新配方"&&!model.ApplyAgentDraftCommand.CanExecute(),"Applying asks for a mode and prevents repeated application");
|
||
Save(choice,"sop-agent-apply-choice");
|
||
choice.GetVisualDescendants().OfType<Button>().Single(b=>b.Name==buttonName)
|
||
.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
if(completed)
|
||
{
|
||
for(var i=0;i<100&&!dialog.OwnedWindows.Any();i++)await Task.Delay(10);
|
||
var notice=dialog.OwnedWindows.Single();
|
||
Check(notice.Title=="配方更新完成"&¬ice.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text?.Contains("保存")==true),
|
||
"Successful application displays a completion notice with an explicit save reminder");
|
||
Save(notice,"sop-agent-apply-completed");
|
||
notice.GetVisualDescendants().OfType<Button>().Single()
|
||
.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
}
|
||
await Task.Delay(20);
|
||
}
|
||
await ApplyDraft("AgentApplyCancelButton",false);
|
||
Check(model.Recipe.Steps.Count==originalCount&&model.ApplyAgentDraftCommand.CanExecute(),"Cancelling the apply dialog preserves the recipe and draft");
|
||
// 下拉框已绑定时也需要收到通知,切换标签页可能重新绑定而掩盖候选未刷新的问题。
|
||
var notifiedOfGeneratedRegion=false;
|
||
void OnRegionNamesChanged(object? sender,System.ComponentModel.PropertyChangedEventArgs e)
|
||
{
|
||
if(e.PropertyName==nameof(RecipeNode.RegionNames))
|
||
notifiedOfGeneratedRegion|=model.Recipe.RegionNames.Contains("料盒2");
|
||
}
|
||
model.Recipe.PropertyChanged+=OnRegionNamesChanged;
|
||
await ApplyDraft("AgentApplyAppendButton",true);
|
||
model.Recipe.PropertyChanged-=OnRegionNamesChanged;
|
||
Check(notifiedOfGeneratedRegion,"Applying a generated region refreshes the existing dropdown bindings");
|
||
Check(model.Recipe.Steps.Count==originalCount+2&&model.Recipe.Steps[0].Name=="装配","Applying generated steps preserves existing steps and appends the draft");
|
||
Check(model.Recipe.Steps[originalCount].Description=="把连接器放入盒子,盒内可见连接器"&&model.Recipe.Steps[originalCount].Detection?.Method=="hand_leave_region","Edited draft description becomes the D3 criterion with a hand trigger");
|
||
// 同时核对区域列表、触发区与送检区,覆盖草稿写入和下拉候选刷新。
|
||
tabs.SelectedItem=tabs.Items.OfType<TabItem>().Single(t=>Equals(t.Header,"步骤"));
|
||
model.Recipe.SelectedStep=model.Recipe.Steps[originalCount+1];
|
||
await Task.Delay(30);
|
||
var regionList=editor.FindControl<ListBox>("StepRegionNavigation")!;
|
||
var triggerRegion=editor.FindControl<Grid>("TriggerRegionRow")!.Children.OfType<ComboBox>().Single();
|
||
var imageRegion=editor.FindControl<ComboBox>("AiImageRegionPicker")!;
|
||
Check(regionList.Items.OfType<RegionNode>().Any(r=>r.Key=="料盒2"&&r.X1==670&&r.X2==730)
|
||
&&Equals(triggerRegion.SelectedItem,"料盒2")&&Equals(imageRegion.SelectedItem,"料盒2"),
|
||
"A generated region appears in the region list and is selected for the step trigger and image crop");
|
||
// 区域位于缩图右边界之外,关键帧必须保留原视频坐标下的画面和原证据时间。
|
||
var savedStep=model.Recipe.Steps[originalCount+1];
|
||
Check(savedStep.KeyFrameImage?.PixelSize==new PixelSize(800,600)&&savedStep.KeyFrameSeconds==3.9,
|
||
"Applied keyframe keeps the original video resolution and evidence timestamp");
|
||
tabs.SelectedItem=tabs.Items.OfType<TabItem>().Single(t=>Equals(t.Header,"Agent助手"));
|
||
model.ApplyAgentDraftCommand.Execute();
|
||
Check(model.Recipe.Steps.Count==originalCount+2&&!model.ApplyAgentDraftCommand.CanExecute(),"A draft cannot be applied twice");
|
||
Check(File.ReadAllBytes(configPath).SequenceEqual(before),"Adding draft steps still requires explicit recipe save");
|
||
client.Hold=false;client.MergeChat=true;
|
||
var appliedId=model.Recipe.Steps[originalCount].Id;
|
||
model.Recipe.Steps[originalCount].AiImageMode="hand";
|
||
model.Recipe.Steps[originalCount].Detection!.StableFrames=7;
|
||
await SendChat("把这两步合并成一步");
|
||
Check(client.ChatRequest?.ImageScopes?[0] is {Mode:"hand"},"Chat receives an applied step's hand-follow image mode rather than assuming fixed crop");
|
||
Check(model.AgentDraftSteps.Count==1&&model.Recipe.Steps.Count==originalCount+2&&model.AgentApplyLabel=="更新配方",
|
||
"Chat can merge an already applied draft without silently changing recipe steps");
|
||
await ApplyDraft("AgentApplyAppendButton",true);
|
||
Check(model.Recipe.Steps.Count==originalCount+3&&model.Recipe.Steps[originalCount].Id==appliedId,
|
||
"Appending a chat revision preserves previously added recipe steps");
|
||
var latestNode=model.Recipe.Steps.Last();
|
||
await SendChat("继续保持合并为一步");
|
||
await ApplyDraft("AgentApplyOverwriteButton",true);
|
||
Check(model.Recipe.Steps.Count==1&&ReferenceEquals(model.Recipe.Steps[0],latestNode)&&latestNode.Id==1,
|
||
"Overwrite replaces all existing recipe steps and keeps the current node with continuous numbering");
|
||
Check(model.Recipe.Steps[0].AiImageMode=="hand"&&model.Recipe.Steps[0].Detection?.StableFrames==7,
|
||
"Chat revisions preserve existing image delivery and trigger stability settings");
|
||
Check(File.ReadAllBytes(configPath).SequenceEqual(before),"Chat revisions never save the recipe automatically");
|
||
model.ClearAgentChatCommand.Execute();
|
||
Check(model.AgentChatMessages.Count==0&&model.AgentDraftSteps.Count==1,"Clearing chat preserves the current draft");
|
||
foreach(var step in model.Recipe.Steps.ToArray())model.Recipe.RemoveStep(step);
|
||
foreach(var step in originalSteps)model.Recipe.Steps.Add(step);
|
||
model.Recipe.RemoveRegion(model.Recipe.Regions.Single(r=>r.Key=="料盒2"));
|
||
model.Recipe.SelectedStep=model.Recipe.Steps[0];tabs.SelectedIndex=0;
|
||
}
|
||
|
||
private static void Save(Window window,string name)
|
||
{
|
||
window.UpdateLayout();
|
||
using var image=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height));image.Render(window);image.Save(Path.Combine(Output,name+".png"));
|
||
}
|
||
private static async Task ChooseRecipeClose(Window owner,string buttonName)
|
||
{
|
||
for(var i=0;i<100&&!owner.OwnedWindows.Any();i++)await Task.Delay(20);
|
||
var prompt=owner.OwnedWindows.Single();
|
||
var buttons=prompt.GetVisualDescendants().OfType<Button>().ToArray();
|
||
Check(owner.IsVisible&&buttons.Length==2,"关闭保存提示仅有保存并关闭和不保存两个按钮");
|
||
buttons.Single(b=>b.Name==buttonName).RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
}
|
||
private static async Task CheckStepTriggerTabs(App app,IClassicDesktopStyleApplicationLifetime lifetime)
|
||
{
|
||
var recipe=new RecipeNode();
|
||
recipe.AddRegion("work");recipe.AddRegion("finish");
|
||
var step=recipe.AddStep();step.Detection.Method="hand_in_region";
|
||
step.Detection.Region="work";step.Detection.FromRegion="work";step.Detection.ToRegion="finish";
|
||
step.Detection.Hand="left";step.AiImageMode="fixed_region";step.AiImageRegion="work";
|
||
recipe.AddStep().Detection.Method="time_elapsed";
|
||
var config=recipe.ToConfig();config.Sop.Name="区域初始选择";
|
||
app.Container.Resolve<IDialogService>().ShowDialog("RecipeEditorDialog",new DialogParameters
|
||
{{"directory",new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!).RecipesDirectory},
|
||
{"config",config},{"new",true}},_=>{});
|
||
await Task.Delay(60);
|
||
var dialog=lifetime.Windows.OfType<RecipeDialogWindow>().Single();
|
||
var editor=dialog.GetVisualDescendants().OfType<RecipeEditor>().Single();
|
||
var model=(RecipeEditorViewModel)editor.DataContext!;
|
||
var first=model.Recipe.Steps[0];var second=model.Recipe.Steps[1];
|
||
try
|
||
{
|
||
var tabs=editor.GetVisualDescendants().OfType<TabControl>().First();
|
||
var picker=editor.FindControl<ComboBox>("StepTriggerMethodPicker")!;
|
||
var selections=editor.FindControl<ScrollViewer>("StepParameters")!.GetVisualDescendants()
|
||
.OfType<ComboBox>().Select(c=>(Picker:c,Selected:c.SelectedItem)).ToArray();
|
||
Check(selections.Select(s=>s.Selected?.ToString()).SequenceEqual(
|
||
new[]{"hand_in_region","work","work","finish","left","fixed_region","work"}),
|
||
"Step selectors initially display all configured values");
|
||
Check(editor.FindControl<Grid>("TriggerRegionRow")!.GetVisualDescendants().OfType<ComboBox>().Single().SelectedItem?.ToString()=="work",
|
||
"Opening a recipe through Prism immediately displays the configured trigger region");
|
||
void CheckSelection(string expected)
|
||
{
|
||
Check(picker.SelectedItem?.ToString()==expected,"Trigger selection survives tab changes: "+expected);
|
||
Check(picker.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text==
|
||
ConditionMethodLabels.Converter.Convert(expected,typeof(string),null,System.Globalization.CultureInfo.InvariantCulture)?.ToString()),
|
||
"Trigger label remains displayed after tab changes: "+expected);
|
||
Check(model.Recipe.SelectedStep!.Detection.Method==expected,"Tab changes preserve the stored trigger method");
|
||
}
|
||
CheckSelection(first.Detection.Method);
|
||
for(var index=1;index<tabs.Items.Count;index++)
|
||
{
|
||
tabs.SelectedIndex=index;await Task.Delay(30);
|
||
tabs.SelectedIndex=0;await Task.Delay(30);
|
||
CheckSelection(first.Detection.Method);
|
||
Check(selections.All(s=>Equals(s.Picker.SelectedItem,s.Selected)),"Region, hand and image selectors retain their selections after tab changes");
|
||
}
|
||
model.Recipe.SelectedStep=second;await Task.Delay(30);CheckSelection("time_elapsed");
|
||
picker.SelectedItem="hand_move";await Task.Delay(30);CheckSelection("hand_move");
|
||
tabs.SelectedIndex=1;await Task.Delay(30);tabs.SelectedIndex=0;await Task.Delay(30);
|
||
CheckSelection("hand_move");
|
||
model.Recipe.SelectedStep=first;await Task.Delay(30);CheckSelection("hand_in_region");
|
||
|
||
// 通过实际鼠标点击验证色块能打开调色板,再从预设色列表选色并核对配方值。
|
||
var region = model.Recipe.SelectedRegion!;
|
||
var colorPicker = editor.FindControl<ScrollViewer>("RegionParameters")!.GetVisualDescendants()
|
||
.OfType<ColorPicker>().Single();
|
||
colorPicker.BringIntoView();
|
||
dialog.UpdateLayout();
|
||
var swatch = colorPicker.GetVisualDescendants().OfType<DropDownButton>().Single();
|
||
var point = swatch.TranslatePoint(new Point(swatch.Bounds.Width / 2, swatch.Bounds.Height / 2), dialog)!.Value;
|
||
dialog.MouseDown(point, MouseButton.Left);
|
||
dialog.MouseUp(point, MouseButton.Left);
|
||
await Task.Delay(30);
|
||
Check(swatch.Flyout is Flyout { IsOpen: true }, "点击颜色块打开调色板");
|
||
var flyout = (Flyout)swatch.Flyout!;
|
||
var colorTabs = ((Control)flyout.Content!).GetVisualDescendants().OfType<TabControl>().Single();
|
||
colorTabs.SelectedIndex = 1;
|
||
dialog.UpdateLayout();
|
||
var colors = colorTabs.GetVisualDescendants().OfType<ListBox>().Single();
|
||
var chosen = colors.Items.OfType<Color>().First(color => color != colorPicker.Color && color.A == byte.MaxValue);
|
||
colors.SelectedItem = chosen;
|
||
Check(region.Color == $"#{chosen.R:X2}{chosen.G:X2}{chosen.B:X2}" && region.Brush.Color == chosen,
|
||
"调色板选色更新配方中的颜色文本和区域预览");
|
||
flyout.Hide();
|
||
|
||
// 比较提示出现与清除时的编辑区位置和尺寸,防止顶栏提示导致界面跳动。
|
||
dialog.UpdateLayout();
|
||
var editBounds = tabs.Bounds;
|
||
var recipeName = model.Recipe.Name;
|
||
model.Recipe.Name = "";
|
||
dialog.UpdateLayout();
|
||
Check(model.NameValidationMessage.Length > 0 && tabs.Bounds == editBounds, "配方名校验提示不改变编辑区布局");
|
||
model.Recipe.Name = recipeName;
|
||
model.SaveCommand.Execute();
|
||
dialog.UpdateLayout();
|
||
Check(model.SaveStatus.StartsWith("已保存") && tabs.Bounds == editBounds, "保存提示不改变编辑区布局");
|
||
first.Name += "修改";
|
||
dialog.UpdateLayout();
|
||
Check(model.SaveStatus.Length == 0 && tabs.Bounds == editBounds, "清除保存提示不改变编辑区布局");
|
||
}
|
||
finally { await model.ShutdownAsync();dialog.Close(); }
|
||
}
|
||
|
||
private static async Task CheckRecipeClose(App app,IClassicDesktopStyleApplicationLifetime lifetime)
|
||
{
|
||
var root=Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!;
|
||
var store=new RecipeWorkspace(root);
|
||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name="Prism关闭保存";
|
||
var callbacks=0;
|
||
var dialogs=app.Container.Resolve<IDialogService>();
|
||
dialogs.ShowDialog("RecipeEditorDialog",new DialogParameters{{"directory",store.RecipesDirectory},{"new",true},{"config",config},
|
||
{"onSaved",new Action<string>(_=>callbacks++)}},_=>{});
|
||
await Task.Delay(80);
|
||
var modal=lifetime.Windows.OfType<RecipeDialogWindow>().Single();
|
||
// 先修改配方,触发有未保存改动时的关闭确认。
|
||
((RecipeEditorViewModel)modal.DataContext!).Recipe.AddStepCommand.Execute();
|
||
((RecipeEditorViewModel)modal.DataContext!).CloseCommand.Execute();
|
||
await ChooseRecipeClose(modal,"SaveRecipeAndCloseButton");
|
||
for(var i=0;i<100&&lifetime.Windows.Contains(modal);i++)await Task.Delay(20);
|
||
Check(!lifetime.Windows.Contains(modal)&&File.Exists(store.ConfigPath(config.Sop.Name))&&callbacks==1,
|
||
"Prism关闭按钮确认后保存一次并正常关闭");
|
||
// 从磁盘回读,确认关闭时保存也会自动记录本地修订日期。
|
||
var saved = SopHelper.Engine.Sop.SopConfigLoader.Load(store.ConfigPath(config.Sop.Name));
|
||
Check(saved.Sop.RevisionDate == DateTime.Today.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture),
|
||
"保存配方后写入本地修订日期");
|
||
dialogs.ShowDialog("RecipeEditorDialog",new DialogParameters{{"directory",store.RecipesDirectory},{"new",false},{"config",config},
|
||
{"path",store.ConfigPath(config.Sop.Name)}},_=>{});
|
||
await Task.Delay(80);
|
||
modal=lifetime.Windows.OfType<RecipeDialogWindow>().Single();
|
||
var before=File.ReadAllBytes(store.ConfigPath(config.Sop.Name));
|
||
((RecipeEditorViewModel)modal.DataContext!).Recipe.AddStepCommand.Execute();
|
||
modal.Close();
|
||
await ChooseRecipeClose(modal,"DiscardRecipeAndCloseButton");
|
||
for(var i=0;i<100&&lifetime.Windows.Contains(modal);i++)await Task.Delay(20);
|
||
Check(!lifetime.Windows.Contains(modal)&&before.SequenceEqual(File.ReadAllBytes(store.ConfigPath(config.Sop.Name))),
|
||
"Prism右上角关闭确认不保存后释放资源并保留原文件");
|
||
}
|
||
/// <summary>在应用启动前准备隔离的账号文件,覆盖已有安装从默认关闭到启用的持久化。</summary>
|
||
private static void PrepareAutoLogin(string root)
|
||
{
|
||
var path = Path.Combine(root, "workspace", "users.json");
|
||
var access = new UserAccess(path);
|
||
access.Setup("auto-admin", "AdminPassword123");
|
||
access.SaveUser("auto-operator", "OperatorPassword123", UserRole.Operator);
|
||
Check(new UserAccess(path).AutoLoginUserName is null, "已有账号且未配置时默认关闭自动登录");
|
||
access.SaveAutoLogin("auto-operator");
|
||
}
|
||
|
||
/// <summary>通过真实启动和设置视图验证自动登录角色、手动退出、表单校验及撤销配置。</summary>
|
||
private static async Task CheckAutoLogin(App app)
|
||
{
|
||
var access = UserAccess.Current;
|
||
var path = Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!, "workspace", "users.json");
|
||
Check(access.User is { Name: "auto-operator", Role: UserRole.Operator }, "应用启动时使用所选操作员及其权限");
|
||
try
|
||
{
|
||
access.SaveAutoLogin("auto-admin");
|
||
throw new Exception("操作员修改了自动登录配置");
|
||
}
|
||
catch (UnauthorizedAccessException)
|
||
{
|
||
Check(access.AutoLoginUserName == "auto-operator", "操作员不能直接修改自动登录配置");
|
||
}
|
||
|
||
access.Logout();
|
||
Check(!access.IsAuthenticated && access.AutoLoginUserName == "auto-operator", "手动退出清除当前会话并保留下次启动配置");
|
||
Check(access.Login("auto-admin", "AdminPassword123"), "管理员可以手动切换身份");
|
||
var view = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(app.Container.Resolve<SopPageViewModel>());
|
||
var window = new Window { Content = view, Width = 900, Height = 900 };
|
||
window.Show();
|
||
try
|
||
{
|
||
await Task.Delay(60);
|
||
var toggle = view.FindControl<ToggleSwitch>("AutoLoginToggle")!;
|
||
var users = view.FindControl<ComboBox>("AutoLoginUserInput")!;
|
||
var save = view.FindControl<Button>("SaveAutoLoginButton")!;
|
||
void Save() => save.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
|
||
Check(toggle.IsChecked == true && users.IsEffectivelyVisible && Equals(users.SelectedItem, "auto-operator"),
|
||
"设置页还原开关与已选用户");
|
||
toggle.IsChecked = false;
|
||
await Task.Delay(40);
|
||
Check(!users.IsEffectivelyVisible, "关闭开关后隐藏用户下拉框");
|
||
Save();
|
||
Check(new UserAccess(path).AutoLoginUserName is null, "保存关闭后清除持久化配置");
|
||
|
||
toggle.IsChecked = true;
|
||
await Task.Delay(40);
|
||
Check(users.IsEffectivelyVisible && users.Items.Cast<string>().SequenceEqual(new[] { "auto-admin", "auto-operator" }),
|
||
"打开开关后可从现有账号中选择");
|
||
Save();
|
||
Check(view.FindControl<TextBlock>("AutoLoginStatus")!.Text == "请选择自动登录用户。"
|
||
&& new UserAccess(path).AutoLoginUserName is null, "开启时必须选择用户才能保存");
|
||
users.SelectedItem = "auto-operator";
|
||
Save();
|
||
Check(new UserAccess(path).AutoLoginUserName == "auto-operator" && access.IsAdministrator,
|
||
"设置页保存所选用户,当前会话保持管理员身份");
|
||
|
||
access.SaveUser("auto-operator", "", UserRole.Engineer);
|
||
Check(new UserAccess(path).AutoLoginUserName is null && toggle.IsChecked == false, "变更角色时撤销旧的自动登录并刷新界面");
|
||
access.SaveAutoLogin("auto-operator");
|
||
access.SaveUser("auto-operator", "ResetPassword123", UserRole.Engineer);
|
||
Check(new UserAccess(path).AutoLoginUserName is null, "重置密码时撤销自动登录");
|
||
access.SaveAutoLogin("auto-operator");
|
||
access.DeleteUser("auto-operator");
|
||
access.SaveUser("auto-operator", "OperatorPassword123", UserRole.Operator);
|
||
Check(new UserAccess(path).AutoLoginUserName is null, "删除后重建同名账号不会继承自动登录");
|
||
}
|
||
finally { window.Close(); }
|
||
}
|
||
|
||
/// <summary>验证角色矩阵、持久化及绕过 CanExecute 的直接调用;仅操作隔离的测试工作区。</summary>
|
||
private static async Task CheckPermissions(App app, Window window)
|
||
{
|
||
var access = UserAccess.Current;
|
||
var model = app.Container.Resolve<SopPageViewModel>();
|
||
var navigation = app.Container.Resolve<NavigationModel>();
|
||
async Task CheckPermissionPrompt(string message)
|
||
{
|
||
await Task.Delay(40);
|
||
var prompts = window.OwnedWindows.OfType<SopHelper.VVMs.MainWindow.PermissionDeniedWindow>().ToArray();
|
||
Check(prompts.Length == 1 && prompts[0].IsVisible && prompts[0].Title == "无权限", message);
|
||
var prompt = prompts[0];
|
||
using var rendered = new RenderTargetBitmap(new PixelSize(400, (int)prompt.Bounds.Height));
|
||
rendered.Render(prompt);
|
||
var output = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(output);
|
||
rendered.Save(Path.Combine(output, "permission-denied.png"));
|
||
prompt.GetVisualDescendants().OfType<Button>().Single(b => b.Name == "ConfirmPermissionDeniedButton").RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
await Task.Delay(20);
|
||
Check(!prompt.IsVisible, "确定按钮关闭权限提示");
|
||
}
|
||
void Denied(Action action, string message)
|
||
{
|
||
try { action(); throw new Exception("未拦截:" + message); }
|
||
catch (Exception error) when (error is UnauthorizedAccessException or InvalidOperationException or ArgumentException)
|
||
{ Check(true, message); }
|
||
}
|
||
Check(!access.IsAuthenticated && model.StartStopCommand.CanExecute(), "未登录保留启动按钮用于提示登录");
|
||
access.Setup("admin", "AdminPassword123");
|
||
access.SaveUser("engineer", "EngineerPassword123", UserRole.Engineer);
|
||
access.SaveUser("operator", "OperatorPassword123", UserRole.Operator);
|
||
Check(access.Users().Count == 3 && access.IsAdministrator && model.NewRecipeCommand.CanExecute(), "管理员创建三类账号并可编辑配方");
|
||
Denied(() => access.SaveUser("admin", "", UserRole.Operator), "不能降级最后一名管理员");
|
||
Denied(() => access.DeleteUser("admin"), "不能删除当前账号");
|
||
var usersPath = Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!, "workspace", "users.json");
|
||
Check(!File.ReadAllText(usersPath).Contains("AdminPassword123"), "账号文件不保存明文密码");
|
||
var restored = new UserAccess(usersPath);
|
||
Check(!restored.Login("admin", "wrong") && restored.Login("ADMIN", "AdminPassword123"), "持久化账号正确验证密码并支持用户名大小写");
|
||
Check(access.Login("engineer", "EngineerPassword123") && access.CanConfigure && !access.IsAdministrator, "工艺师具有设置权限且没有管理员权限");
|
||
navigation.Navigate("RuntimeSettings");
|
||
Check(navigation.Target?.ViewName == "RuntimeSettings" && model.NewRecipeCommand.CanExecute(), "工艺师可访问设置与编辑配方");
|
||
Check(model.ImportRecipeCommand.CanExecute() && model.ExportRecipeCommand.CanExecute(), "工艺师可导入导出配方");
|
||
var settings = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(model);
|
||
var dialog = new Window { Content = settings, Width = 900, Height = 900 };
|
||
dialog.Show(); await Task.Delay(60);
|
||
Check(settings.FindControl<NumericUpDown>("ResetDelayInput")!.IsEffectivelyEnabled, "工艺师可修改运行参数");
|
||
window.GetVisualDescendants().OfType<Button>().Single(b => Equals(b.Content, "人员管理"))
|
||
.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
await CheckPermissionPrompt("工艺师点击人员管理弹出无权限提示");
|
||
Denied(() => access.SaveUser("illegal", "Password123", UserRole.Administrator), "工艺师不能管理人员");
|
||
var editor = new RecipeEditorViewModel();
|
||
editor.OnDialogOpened(new DialogParameters { { "new", true } });
|
||
var agentModel = editor.AgentModel; editor.AgentModel = "forbidden-model";
|
||
Check(editor.AgentModel == agentModel && !editor.CanChangeAgentModels, "工艺师不能修改 Agent 模型设置");
|
||
var editorView = new SopHelper.VVMs.RecipeEditor.RecipeEditor { DataContext = editor };
|
||
var modelSettings = editorView.FindControl<Expander>("AgentSettingsExpander")!;
|
||
modelSettings.IsExpanded = true;
|
||
await Task.Delay(250);
|
||
Check(!modelSettings.IsExpanded, "无权限时模型设置保持收起");
|
||
await CheckPermissionPrompt("工艺师点击 Agent 模型设置弹出权限提示");
|
||
var stride = model.FrameStride; model.FrameStride = stride == 1 ? 2 : 1;
|
||
Check(model.FrameStride != stride, "工艺师可以保存运行设置");
|
||
access.Login("operator", "OperatorPassword123"); await Task.Delay(50);
|
||
Check(!access.CanConfigure && navigation.Target?.ViewName == "SopPage", "切换操作员后立即返回运行页");
|
||
navigation.Navigate("RuntimeSettings");
|
||
Check(navigation.Target?.ViewName == "SopPage", "操作员不能进入设置页");
|
||
await CheckPermissionPrompt("设置入口弹出无权限窗口");
|
||
Check(model.NewRecipeCommand.CanExecute() && model.EditRecipeCommand.CanExecute()
|
||
&& model.ApplyRecipeCommand.CanExecute() && model.ResetCountsCommand.CanExecute()
|
||
&& model.PlayStandardSopCommand.CanExecute() && model.ImportRecipeCommand.CanExecute()
|
||
&& model.ExportRecipeCommand.CanExecute(), "无权限按钮保留点击以显示拒绝提示");
|
||
Check(model.StartStopCommand.CanExecute(), "操作员可启动已配置的流程");
|
||
model.IsRunning = true;
|
||
Check(model.StartStopCommand.CanExecute() && !((SopHelper.VVMs.MainWindow.MainWindowViewModel)window.DataContext!).CanChangeAccount,
|
||
"运行中操作员可以停止,且主窗口禁止切换身份");
|
||
model.IsRunning = false;
|
||
var previousStride = model.FrameStride;
|
||
var previousRecipe = model.SelectedRecipe;
|
||
model.FrameStride = previousStride == 1 ? 2 : 1; model.SelectedRecipe = "forbidden.yaml";
|
||
model.NewRecipeCommand.Execute(); model.EditRecipeCommand.Execute(); model.ApplyRecipeCommand.Execute();
|
||
model.ImportRecipeCommand.Execute(); model.ExportRecipeCommand.Execute();
|
||
Check(model.FrameStride == previousStride && model.SelectedRecipe == previousRecipe, "直接调用和属性写入不能绕过操作员限制");
|
||
await CheckPermissionPrompt("受限配方按钮弹出提示,连续点击只显示一个窗口");
|
||
Check(!settings.FindControl<NumericUpDown>("ResetDelayInput")!.IsEffectivelyEnabled, "已打开的运行设置同步禁用");
|
||
Denied(() => access.Users(), "操作员不能读取人员管理列表");
|
||
access.Logout();
|
||
Check(model.StartStopCommand.CanExecute() && model.NewRecipeCommand.CanExecute(), "退出登录仍保留按钮点击反馈");
|
||
model.StartStopCommand.Execute();
|
||
Check(!model.IsRunning, "未登录直接执行启动命令也被拦截");
|
||
await CheckPermissionPrompt("未登录启动弹出权限提示");
|
||
access.Login("admin", "AdminPassword123");
|
||
var adminEditor = new RecipeEditorViewModel();
|
||
adminEditor.OnDialogOpened(new DialogParameters { { "new", true } });
|
||
adminEditor.AgentModel = "admin-model";
|
||
Check(adminEditor.AgentModel == "admin-model" && adminEditor.CanChangeAgentModels, "管理员可以保存 Agent 模型设置");
|
||
access.SaveUser("operator", "ResetPassword123", UserRole.Operator);
|
||
Check(!restored.Login("operator", "ResetPassword123") && new UserAccess(usersPath).Login("operator", "ResetPassword123"), "重置密码持久化并使用新密码登录");
|
||
access.DeleteUser("operator");
|
||
Check(!new UserAccess(usersPath).Login("operator", "ResetPassword123"), "删除账号后不能重新登录");
|
||
dialog.Close();
|
||
await Task.Delay(60);
|
||
var accountDialog = new SopHelper.VVMs.MainWindow.AccountWindow(true);
|
||
accountDialog.Show(window); await Task.Delay(60);
|
||
using (var accountImage = new RenderTargetBitmap(new PixelSize(440,560)))
|
||
{
|
||
accountImage.Render(accountDialog);
|
||
var output = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(output);
|
||
accountImage.Save(Path.Combine(output, "user-management.png"));
|
||
}
|
||
accountDialog.Close();
|
||
using var rendered = new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width, (int)window.Bounds.Height));
|
||
rendered.Render(window);
|
||
var screenshots = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(screenshots);
|
||
rendered.Save(Path.Combine(screenshots, "user-permissions.png"));
|
||
}
|
||
|
||
/// <summary>检查全部角色的本人改密、失败时不落盘、角色隔离,以及真实窗口保存入口。</summary>
|
||
private static async Task CheckOwnPasswords(Window window)
|
||
{
|
||
var access = UserAccess.Current;
|
||
var path = Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!, "workspace", "users.json");
|
||
foreach (var role in Enum.GetValues<UserRole>())
|
||
access.SaveUser("self-" + role, "OriginalPassword123", role);
|
||
access.Logout();
|
||
bool Rejected(Action action)
|
||
{
|
||
try { action(); return false; }
|
||
catch (Exception error) when (error is UnauthorizedAccessException or ArgumentException) { return true; }
|
||
}
|
||
Check(Rejected(() => access.ChangeOwnPassword("", "UpdatedPassword123", "UpdatedPassword123")), "未登录不能修改本人密码");
|
||
foreach (var role in Enum.GetValues<UserRole>())
|
||
{
|
||
var name = "self-" + role;
|
||
Check(access.Login(name, "OriginalPassword123"), "本人改密前登录:" + role);
|
||
var before = File.ReadAllText(path);
|
||
Check(Rejected(() => access.ChangeOwnPassword("wrong", "UpdatedPassword123", "UpdatedPassword123"))
|
||
&& Rejected(() => access.ChangeOwnPassword("OriginalPassword123", "UpdatedPassword123", "different"))
|
||
&& Rejected(() => access.ChangeOwnPassword("OriginalPassword123", "short", "short"))
|
||
&& File.ReadAllText(path) == before, "原密码、确认密码和密码长度校验失败均不写盘:" + role);
|
||
access.ChangeOwnPassword("OriginalPassword123", "UpdatedPassword123", "UpdatedPassword123");
|
||
var saved = new UserAccess(path);
|
||
Check(access.User == new UserSummary(name, role) && !saved.Login(name, "OriginalPassword123")
|
||
&& saved.Login(name, "UpdatedPassword123") && saved.User!.Role == role,
|
||
"三类角色均可改密,新密码持久化且原密码失效、身份角色保持:" + role);
|
||
Check(saved.Login("admin", "AdminPassword123"), "本人改密不改变其他账号密码:" + role);
|
||
}
|
||
await Task.Delay(40);
|
||
window.GetVisualDescendants().OfType<Button>().Single(b => Equals(b.Content, "修改密码"))
|
||
.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
await Task.Delay(40);
|
||
var dialog = window.OwnedWindows.OfType<SopHelper.VVMs.MainWindow.ChangePasswordWindow>().Single();
|
||
TextBox Input(string name) => dialog.GetVisualDescendants().OfType<TextBox>().Single(b => b.Name == name);
|
||
var save = dialog.GetVisualDescendants().OfType<Button>().Single(b => b.Name == "SaveOwnPasswordButton");
|
||
var status = dialog.GetVisualDescendants().OfType<TextBlock>().Single(b => b.Name == "ChangePasswordStatus");
|
||
Input("CurrentPasswordInput").Text = "UpdatedPassword123";
|
||
Input("NewPasswordInput").Text = "UiChangedPassword123";
|
||
Input("ConfirmPasswordInput").Text = "mismatch";
|
||
save.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
Check(status.Text!.Contains("不一致") && save.IsEnabled, "改密窗口显示两次密码不一致并允许重试");
|
||
Input("ConfirmPasswordInput").Text = "UiChangedPassword123";
|
||
save.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
await Task.Delay(40);
|
||
Check(status.Text!.Contains("成功") && !save.IsEnabled
|
||
&& dialog.GetVisualDescendants().OfType<TextBox>().All(b => b.PasswordChar == '●' && b.Text == "")
|
||
&& new UserAccess(path).Login("self-Operator", "UiChangedPassword123"),
|
||
"操作员通过主窗口修改本人密码,保存成功后清空密码框并显示成功提示");
|
||
using (var rendered = new RenderTargetBitmap(new PixelSize(440, (int)dialog.Bounds.Height)))
|
||
{
|
||
rendered.Render(dialog);
|
||
var output = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(output);
|
||
rendered.Save(Path.Combine(output, "change-own-password.png"));
|
||
}
|
||
dialog.Close();
|
||
access.Login("admin", "AdminPassword123");
|
||
}
|
||
|
||
/// <summary>通过真实登录控件验证首次建号、账号选择、密码验证及切换时的口令清理。</summary>
|
||
private static async Task CheckLoginUserSelection(Window window)
|
||
{
|
||
T Control<T>(Window dialog, string name) where T : Avalonia.Controls.Control =>
|
||
dialog.GetVisualDescendants().OfType<T>().Single(c => c.Name == name);
|
||
void Submit(Window dialog) => Control<Button>(dialog, "SubmitAccountButton")
|
||
.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||
var access = UserAccess.Current;
|
||
var setup = new SopHelper.VVMs.MainWindow.AccountWindow();
|
||
setup.Show(window); await Task.Delay(40);
|
||
Check(setup.Title == "创建首个管理员" && !setup.GetVisualDescendants().OfType<ComboBox>().Any(), "首次创建管理员仍使用用户名输入框");
|
||
Control<TextBox>(setup, "AccountNameInput").Text = "admin";
|
||
Control<TextBox>(setup, "AccountPasswordInput").Text = "AdminPassword123";
|
||
Submit(setup); await Task.Delay(20);
|
||
Check(!setup.IsVisible && access.IsAdministrator, "首次建号能够输入用户名并成功登录");
|
||
access.SaveUser("engineer", "EngineerPassword123", UserRole.Engineer);
|
||
access.SaveUser("operator", "OperatorPassword123", UserRole.Operator);
|
||
access.SaveUser("deleted", "DeletedPassword123", UserRole.Operator);
|
||
access.DeleteUser("deleted");
|
||
access.Logout();
|
||
Check(access.LoginUserNames().SequenceEqual(new[] { "admin", "engineer", "operator" }), "未登录可获取现有用户名,删除的账号不出现在列表");
|
||
var dialog = new SopHelper.VVMs.MainWindow.AccountWindow();
|
||
dialog.Show(window); await Task.Delay(40);
|
||
var users = Control<ComboBox>(dialog, "AccountUserSelector");
|
||
var password = Control<TextBox>(dialog, "AccountPasswordInput");
|
||
Check(users.ItemsSource!.Cast<string>().SequenceEqual(access.LoginUserNames())
|
||
&& !dialog.GetVisualDescendants().OfType<TextBox>().Any(t => t.Name == "AccountNameInput"), "普通登录使用已有用户名下拉框,移除手动用户名输入");
|
||
users.SelectedItem = "engineer"; password.Text = "wrong";
|
||
Submit(dialog);
|
||
Check(dialog.IsVisible && !access.IsAuthenticated && Control<TextBlock>(dialog, "AccountStatus").Text == "用户名或密码错误", "选择账号后仍必须验证密码");
|
||
users.SelectedItem = "operator";
|
||
Check(password.Text == "", "选择其他用户名时清空已输入的密码");
|
||
users.SelectedIndex = -1; Submit(dialog);
|
||
Check(Control<TextBlock>(dialog, "AccountStatus").Text == "请选择用户名" && !access.IsAuthenticated, "没有选择用户名时提示选择");
|
||
users.SelectedItem = "operator";
|
||
users.IsDropDownOpen = true; await Task.Delay(60);
|
||
using (var rendered = new RenderTargetBitmap(new PixelSize(440,340)))
|
||
{
|
||
rendered.Render(dialog);
|
||
var output = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(output);
|
||
rendered.Save(Path.Combine(output, "login-user-selection.png"));
|
||
}
|
||
users.IsDropDownOpen = false;
|
||
password.Text = "OperatorPassword123"; Submit(dialog); await Task.Delay(20);
|
||
Check(!dialog.IsVisible && access.User == new UserSummary("operator", UserRole.Operator), "下拉选择账号并验证正确密码后登录相应角色");
|
||
var switchDialog = new SopHelper.VVMs.MainWindow.AccountWindow();
|
||
switchDialog.Show(window); await Task.Delay(40);
|
||
Check((string?)Control<ComboBox>(switchDialog, "AccountUserSelector").SelectedItem == "operator", "切换用户窗口默认选中当前账号");
|
||
switchDialog.Close();
|
||
}
|
||
|
||
private static void Check(bool condition,string message){if(!condition)throw new Exception(message);Console.WriteLine("PASS: "+message);}
|
||
}
|
||
internal sealed class FakeCamera : ICameraService
|
||
{
|
||
public bool IsConnected{get;private set;}public bool IsGrabbing{get;private set;}
|
||
public event Action<CameraFrame>? FrameArrived;
|
||
public event Action<bool>? ConnectionChanged;
|
||
public event Action<string>? Error {add{}remove{}}
|
||
public List<CameraInfo> Devices {get;set;}=[new(){Index=0,Name="测试相机"}];
|
||
public Task<List<CameraInfo>> EnumerateAsync()=>Task.FromResult(Devices.ToList());
|
||
public int ConnectCount {get;private set;}
|
||
public int ConfigureCount {get;private set;}
|
||
public int DisconnectCount {get;private set;}
|
||
public Task<bool> ConnectAsync(CameraInfo camera){ConnectCount++;IsConnected=true;ConnectionChanged?.Invoke(true);return Task.FromResult(true);}
|
||
public UvcCaptureOptions? LastUsbOptions {get;private set;}
|
||
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options){ConfigureCount++;LastUsbOptions=options with {};return Task.FromResult("test USB mode");}
|
||
public Task<bool> StartAsync(){IsGrabbing=true;return Task.FromResult(true);}
|
||
public void Stop(){IsGrabbing=false;}public void Disconnect(){DisconnectCount++;Stop();IsConnected=false;ConnectionChanged?.Invoke(false);}public int DisposeCount {get;private set;} public void Dispose(){DisposeCount++;Disconnect();}
|
||
private long _id;
|
||
public void Emit(int? objectX=null)
|
||
{
|
||
using var frame=new CameraFrame {FrameId=++_id,Timestamp=DateTime.Now,Bgr=new Mat(480,640,MatType.CV_8UC3,new Scalar(35,60,90))};
|
||
if(objectX is int x)Cv2.Rectangle(frame.Bgr,new OpenCvSharp.Rect(x,40,60,60),new Scalar(0,0,255),-1);
|
||
FrameArrived?.Invoke(frame);
|
||
}
|
||
}
|
||
|
||
internal sealed class UiVisionDecision : SopHelper.Engine.Sop.IVisionDecisionClient
|
||
{
|
||
public TaskCompletionSource Called {get;}=new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
public TaskCompletionSource<SopHelper.Engine.Sop.VisionDecisionResult> Result {get;}=new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
public Task<SopHelper.Engine.Sop.VisionDecisionResult> DecideAsync(SopHelper.Engine.Sop.VisionDecisionRequest request,CancellationToken token)
|
||
{Called.TrySetResult();return Result.Task;}
|
||
}
|
||
|
||
internal sealed class UiSopAgent : ISopVideoDraftClient
|
||
{
|
||
public SopAgentConnection? Connection;
|
||
public SopVideoAnalysisRequest? Request;
|
||
public bool Hold,Held;
|
||
public bool ChatOnly,InvalidChat,MergeChat;
|
||
public SopVideoAnalysisRequest? ChatRequest;
|
||
public Task<SopAgentChatResult> ChatAsync(SopVideoAnalysisRequest request,SopAgentConnection connection,CancellationToken token)
|
||
{
|
||
ChatRequest=request;
|
||
if(Hold){Held=true;return new TaskCompletionSource<SopAgentChatResult>().Task;}
|
||
if(ChatOnly)return Task.FromResult(new SopAgentChatResult("这里是放入和取走两个动作。",null,request.Video.Frames));
|
||
var draft=System.Text.Json.JsonSerializer.Deserialize<SopVideoDraft>(System.Text.Json.JsonSerializer.Serialize(request.CurrentDraft))!;
|
||
draft.Steps[0].Name=InvalidChat?"":"放入连接器";
|
||
if(MergeChat){draft.Steps[0].EndSeconds=draft.Steps[^1].EndSeconds;draft.Steps=draft.Steps.Take(1).ToList();}
|
||
draft.ObservedFrames=request.Video.Frames;
|
||
return Task.FromResult(new SopAgentChatResult(MergeChat?"已合并为一步。":"已修改第一步名称。",draft,request.Video.Frames));
|
||
}
|
||
public Task<SopVideoDraft> AnalyzeAsync(SopVideoAnalysisRequest request,SopAgentConnection connection,CancellationToken token)
|
||
{
|
||
Request=request;Connection=connection;
|
||
if(Hold){Held=true;return new TaskCompletionSource<SopVideoDraft>().Task;}
|
||
return Task.FromResult(new SopVideoDraft{Summary="放入并取走零件",
|
||
ObservedFrames=SopVideoSampler.ReadFrames(request.Video,[0,2,3.9],0,token),
|
||
RegionAdjustments=[new(){Key="料盒2",Name="第二个料盒",X1=670,Y1=4,X2=730,Y2=30,EvidenceFrame=2,Note="取走零件的位置"}],Steps=[
|
||
new(){Name="放入零件",Description="盒子里有零件",StartSeconds=0,EndSeconds=2,Region="work",EvidenceFrame=1},
|
||
new(){Name="取走零件",Description="盒子里没有零件",StartSeconds=2,EndSeconds=4,Region="料盒2",EvidenceFrame=2}]});
|
||
}
|
||
}
|