1038 lines
80 KiB
C#
1038 lines
80 KiB
C#
using Avalonia;
|
|
using Avalonia.Controls;
|
|
using Avalonia.Controls.ApplicationLifetimes;
|
|
using Avalonia.Headless;
|
|
using Avalonia.Media.Imaging;
|
|
using Avalonia.Threading;
|
|
using Prism.Ioc;
|
|
using Prism.Dialogs;
|
|
using SopHelper;
|
|
using SopHelper.Engine.Camera;
|
|
using SopHelper.Engine.Training;
|
|
using SopHelper.Models;
|
|
using SopHelper.Training;
|
|
using SopHelper.VVMs.SopPage;
|
|
using SopHelper.VVMs.RecipeEditor;
|
|
using System.Text.Json;
|
|
using Avalonia.VisualTree;
|
|
using OpenCvSharp;
|
|
using SopHelper.Engine.SopAgent;
|
|
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();
|
|
[STAThread]
|
|
public static int Main(string[] args)
|
|
{
|
|
if(args.Length==2&&args[0]=="--probe-usb-ev")
|
|
{
|
|
try
|
|
{
|
|
var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!;
|
|
var range=type.GetMethod("Query")!.Invoke(null,[int.Parse(args[1])]);
|
|
Console.WriteLine("USB EV capability (read only): "+range);return 0;
|
|
}
|
|
catch(Exception ex) { Console.WriteLine("USB EV probe: "+(ex.InnerException?.Message??ex.Message));return 2; }
|
|
}
|
|
if(args.Length==2&&args[0]=="--probe-usb-low-light")
|
|
{
|
|
try
|
|
{
|
|
var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!;
|
|
var value=type.GetMethod("QueryLowLightCompensation")!.Invoke(null,[int.Parse(args[1])]);
|
|
Console.WriteLine("USB low-light compensation (read only): "+(value is bool enabled ? (enabled ? "on" : "off") : "unavailable"));
|
|
}
|
|
catch(Exception ex){Console.WriteLine("USB low-light probe: "+(ex.InnerException?.Message??ex.Message));}
|
|
return 0;
|
|
}
|
|
_visionOnly=args.Contains("--vision-only");
|
|
_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
|
|
{
|
|
AppBuilder.Configure(()=>new App(Camera)).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);
|
|
}
|
|
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(_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("--usb-capture-only")) { await CheckUsbCapture(app); _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=="SOP 辅助"&&!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(_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=="未应用配方","No recipe is reported active before applying");
|
|
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");
|
|
Check(settings.GetVisualDescendants().OfType<ComboBox>().Count()==2&&settings.GetVisualDescendants().OfType<Slider>().Count()==1,"Camera, recipe 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"&&t.Text==sop.InferenceBackendText)
|
|
&&sop.InferenceBackendText.Contains("手部:")&&sop.InferenceBackendText.Contains("步骤确认:"),
|
|
"Operator page displays the actual inference backends, including CPU fallback");
|
|
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,"Stop command releases acquisition");
|
|
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);
|
|
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();
|
|
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();
|
|
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 recorder=new CameraWindow(new CameraViewModel(new FakeCamera(),Path.Combine(Path.GetTempPath(),"sophelper-avalonia-smoke")));
|
|
recorder.Show();await Task.Delay(100);Save(recorder,"camera");recorder.Close();
|
|
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");
|
|
double[]? drawn=null;var annotation=new AnnotationCanvas {Source=image,TargetName="目标零件 · 支架"};annotation.BoxDrawn+=box=>drawn=box;drawing.Content=annotation;await Task.Delay(60);
|
|
drawing.MouseDown(new Point(100,150),MouseButton.Left);drawing.MouseMove(new Point(300,250));Save(drawing,"annotation-target-drag");drawing.MouseUp(new Point(300,250),MouseButton.Left);
|
|
annotation.Box=drawn;Save(drawing,"annotation-target-saved");
|
|
annotation.Box=[0,0,100,60];Save(drawing,"annotation-target-edge");annotation.Box=null;
|
|
drawing.MouseDown(new Point(300,250),MouseButton.Left);drawing.MouseMove(new Point(100,150));drawing.MouseUp(new Point(100,150),MouseButton.Left);
|
|
Check(drawn is {Length:4}&&drawn.SequenceEqual(new double[]{50,25,150,75}),"Actual annotation drag preserves original-image box coordinates");
|
|
drawn=null;
|
|
drawing.MouseWheel(new Point(150,175),new Vector(0,1));
|
|
drawing.MouseDown(new Point(150,175),MouseButton.Right);drawing.MouseMove(new Point(170,185));drawing.MouseUp(new Point(170,185),MouseButton.Right);
|
|
Check(drawn is null,"Right-button panning never creates an annotation");
|
|
drawing.MouseDown(new Point(350,275),MouseButton.Left);drawing.MouseMove(new Point(110,155));drawing.MouseUp(new Point(110,155),MouseButton.Left);
|
|
Check(drawn is {Length:4}&&drawn.Zip(new double[]{50,25,150,75}).All(p=>Math.Abs(p.First-p.Second)<.001),"Cursor-centered wheel zoom and right-button pan preserve original-image box coordinates");
|
|
using(var nextImage=SopHelper.Presentation.Imaging.BitmapSource.Create(200,100,96,96,SopHelper.Presentation.Imaging.PixelFormats.Bgr24,null,new byte[200*100*3],600))
|
|
{
|
|
annotation.Source=nextImage;drawn=null;
|
|
drawing.MouseDown(new Point(110,155),MouseButton.Left);drawing.MouseUp(new Point(350,275),MouseButton.Left);
|
|
Check(drawn is {Length:4}&&drawn.Zip(new double[]{50,25,150,75}).All(p=>Math.Abs(p.First-p.Second)<.001),"Switching same-size frames retains zoom and pan");
|
|
annotation.ResetView();drawn=null;
|
|
drawing.MouseDown(new Point(100,150),MouseButton.Left);drawing.MouseUp(new Point(300,250),MouseButton.Left);
|
|
Check(drawn is {Length:4}&&drawn.SequenceEqual(new double[]{50,25,150,75}),"Fit-to-window resets both zoom and pan");
|
|
drawing.MouseDown(new Point(200,200),MouseButton.Right);drawing.MouseMove(new Point(220,210));
|
|
annotation.Source=null;drawing.MouseUp(new Point(220,210),MouseButton.Right);annotation.Source=image;drawn=null;
|
|
drawing.MouseDown(new Point(100,150),MouseButton.Left);drawing.MouseUp(new Point(300,250),MouseButton.Left);
|
|
Check(drawn is {Length:4}&&drawn.SequenceEqual(new double[]{50,25,150,75}),"Clearing the image cancels panning and restores the fitted view");
|
|
}
|
|
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 CheckTrainingImport(IClassicDesktopStyleApplicationLifetime lifetime,Window owner,TrainingPage view,SopHelper.Training.MainViewModel trainer)
|
|
{
|
|
var store=new RecipeWorkspace(trainer.Root);var configPath=store.ConfigPath(trainer.RecipeName);
|
|
var config=SopHelper.Engine.Sop.SopConfigLoader.Load(configPath);config.Sop.Parts=["支架","螺丝","测试零件"];
|
|
SopHelper.Engine.Sop.SopConfigLoader.Save(config,configPath);trainer.RefreshPartNames();
|
|
var selectVideo=trainer.SelectImportVideoAsync;
|
|
async Task Import()
|
|
{
|
|
trainer.ImportCommand.Execute();
|
|
for(var i=0;i<400&&(trainer.IsBusy||trainer.IsImporting);i++)await Task.Delay(20);
|
|
Check(!trainer.IsBusy&&!trainer.IsImporting,"Video import finishes without a part picker");
|
|
}
|
|
try
|
|
{
|
|
trainer.SelectImportVideoAsync=()=>Task.FromResult<string?>(null);await Import();
|
|
Check(trainer.Project is null,"Cancelling the video picker leaves the current project unchanged");
|
|
var videoPath=Path.Combine(trainer.Root,"multi-part-test.avi");
|
|
using(var writer=new VideoWriter(videoPath,FourCC.MJPG,10,new OpenCvSharp.Size(64,48)))
|
|
{
|
|
Check(writer.IsOpened(),"Import fixture video opens for writing");
|
|
using var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90));for(var i=0;i<30;i++)writer.Write(frame);
|
|
}
|
|
trainer.SelectImportVideoAsync=()=>Task.FromResult<string?>(videoPath);await Import();
|
|
Check(trainer.Project is {AnnotationVersion:2}&&trainer.Frames.Count>0,"Video import creates an unassigned multi-part project");
|
|
var selector=view.FindControl<ComboBox>("TrainingTargetPart")!;
|
|
selector.SelectedItem="支架";trainer.DrawBox([1,1,60,44]);
|
|
selector.SelectedItem="螺丝";trainer.DrawBox([10,10,25,25]);
|
|
Check(trainer.SelectedFrame!.Objects.Count==2&&trainer.CurrentAnnotations.Count==2&&trainer.SelectedFrame.Status=="auto","A nested second part preserves the first box and requires whole-frame review");
|
|
Check(view.GetVisualDescendants().OfType<AnnotationCanvas>().Single().Annotations!.Count==2,"Annotation canvas receives both part boxes at once");
|
|
trainer.ApproveCommand.Execute();var first=trainer.Project!.FilePath;
|
|
var saved=TrainingProject.Load(first);
|
|
Check(saved.Frames[0].Status=="reviewed"&&saved.Frames[0].Objects.All(o=>o.Status=="reviewed"),"Whole-frame review saves both part labels");
|
|
Save(owner,"multi-part-annotation");
|
|
trainer.AbsentCommand.Execute();
|
|
Check(trainer.SelectedFrame.Objects.Single(o=>o.Label=="支架").Box!=null&&trainer.CurrentBox==null,"Marking the selected part absent preserves other part boxes");
|
|
trainer.Label="支架";trainer.DrawBox([2,2,58,43]);
|
|
Check(trainer.SelectedFrame.Objects.Count==2&&trainer.SelectedFrame.Objects.Single(o=>o.Label=="螺丝").Status=="absent","Redrawing updates only the selected part");
|
|
trainer.SelectedFrame=trainer.Frames[1];trainer.Label="螺丝";trainer.DrawBox([10,10,25,25]);trainer.Label="支架";
|
|
trainer.Load(first,1);Check(trainer.SelectedFrame!.Objects.Single().Label=="螺丝","Reopening preserves per-frame part identities without relabeling");
|
|
var before=File.ReadAllBytes(first);trainer.SelectImportVideoAsync=()=>Task.FromResult<string?>(null);await Import();
|
|
Check(trainer.Project.FilePath==first&&File.ReadAllBytes(first).SequenceEqual(before),"Cancelling a later import preserves every existing annotation");
|
|
}
|
|
finally{trainer.SelectImportVideoAsync=selectVideo;}
|
|
}
|
|
private static async Task CheckTrainingLayout(Window window,TrainingPage view,SopHelper.Training.MainViewModel trainer)
|
|
{
|
|
var width=window.Width;var logs=trainer.Logs;var status=trainer.Status;
|
|
var scroll=(ScrollViewer)view.Content!;var layout=(Grid)scroll.Content!;
|
|
var canvas=view.GetVisualDescendants().OfType<AnnotationCanvas>().Single();
|
|
var tabs=view.GetVisualDescendants().OfType<TabControl>().Single();var selectedTab=tabs.SelectedIndex;
|
|
try
|
|
{
|
|
trainer.Logs="训练日志:"+new string('W',3000);trainer.Status="训练状态:"+new string('W',1000);
|
|
foreach(var size in new[]{1180d,1600d,1000d,1180d})
|
|
{
|
|
window.Width=size;
|
|
for(var tab=0;tab<tabs.ItemCount;tab++)
|
|
{
|
|
tabs.SelectedIndex=tab;await Task.Delay(60);window.UpdateLayout();
|
|
var expected=Math.Max(960,scroll.Viewport.Width);
|
|
Check(Math.Abs(layout.Bounds.Width-expected)<1,
|
|
$"Training layout stays within viewport/minimum width with long logs and status ({size}, tab {tab}); actual={layout.Bounds.Width}, expected={expected}");
|
|
Check(canvas.Bounds.Width>100&&canvas.Bounds.Width<=expected-504,
|
|
"Annotation canvas stays within the center column after resizing and tab changes");
|
|
}
|
|
}
|
|
}
|
|
finally {window.Width=width;trainer.Logs=logs;trainer.Status=status;tabs.SelectedIndex=selectedTab;}
|
|
}
|
|
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;
|
|
}
|
|
|
|
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;
|
|
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=="未应用配方"&&!vm.IsRunning,"Restart restores the last selected recipe without applying it or starting acquisition"));
|
|
File.Delete(store.ConfigPath(name));
|
|
WithVm(vm=>Check(vm.SelectedRecipe is not null&&vm.Recipes.Contains(vm.SelectedRecipe)&&vm.SelectedRecipe!=file,"A deleted preferred recipe falls back to an available recipe"));
|
|
File.WriteAllText(path,"{invalid-json");
|
|
WithVm(vm=>Check(vm.SelectedRecipe is not null&&vm.Recipes.Contains(vm.SelectedRecipe),"Corrupt recipe preference does not prevent startup"));
|
|
}
|
|
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.Hikvision,SerialNumber="camera-preferred",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))!.SerialNumber==preferred.SerialNumber,"Changing camera saves immediately without starting acquisition");
|
|
});
|
|
var reindexed=new CameraInfo {Kind=preferred.Kind,SerialNumber=preferred.SerialNumber,Index=7,Name=preferred.Name};
|
|
WithCameras([reindexed,first],(vm,_)=>Check(ReferenceEquals(vm.SelectedCamera,reindexed),"Restart restores the selected camera by serial number despite enumeration order/index 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"));
|
|
}
|
|
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("artifacts/avalonia-smoke");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 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(150);
|
|
Check(sop.FlowElapsedText!="00:00:00.0"&&sop.StepElapsedText!="00:00:00.0","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(round<=10?sop.AverageDurationText=="00:00:00.0":sop.AverageDurationText!="00:00:00.0","Average display starts only after the eleventh completion");
|
|
}
|
|
Check(sop.StandardDurationText=="00:00:03.2","Runtime displays the remembered standard SOP video duration");
|
|
Check(sop.StepCards.All(c=>c.ElapsedText!="00:00:00.0"),"Completed step cards retain their individual elapsed times");
|
|
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("平均用时")&&texts.Contains("11"),"Operator page renders all five statistics and their bound values");
|
|
Save(window,"runtime-statistics");
|
|
engine.Reset();await Task.Delay(120);
|
|
Check(sop.CompletedCount==11&&sop.StepCards.All(c=>c.ElapsedText=="00:00:00.0"||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 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(){ExposureCompensationEv=double.NaN},new(){ExposureCompensationEv=11}})
|
|
{
|
|
var rejected=false;
|
|
try {invalid.Validate();} catch(ArgumentException){rejected=true;}
|
|
Check(rejected,"Invalid USB capture request is rejected before reaching the driver");
|
|
}
|
|
var thirds=new ExposureCompensationRange(-2,2,4);
|
|
Check(thirds.Encode(-2d/3)==(4UL,-2)&&Math.Abs(ExposureCompensationRange.Decode(4,-2)+2d/3)<0.0001,"EV values convert to the camera's supported step units without changing exposure time");
|
|
var wholeOnly=new ExposureCompensationRange(-2,2,16);
|
|
var rejectedFraction=false;try{wholeOnly.Encode(-1d/3);}catch(NotSupportedException){rejectedFraction=true;}
|
|
Check(rejectedFraction&&wholeOnly.Encode(-1)==(16UL,-1),"Unsupported fractional EV is rejected rather than silently rounded");
|
|
var rejectedRange=false;try{thirds.Encode(-3);}catch(ArgumentOutOfRangeException){rejectedRange=true;}
|
|
Check(rejectedRange,"Requested EV is checked against the actual device range");
|
|
var native=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!;
|
|
Check(native.GetMethod("TrySet")!.Invoke(null,[-1,-1d]) is null,
|
|
"Unavailable exposure compensation silently returns without throwing or writing to a camera");
|
|
Check(native.GetMethod("TrySetLowLightCompensation")!.Invoke(null,[-1,false]) is null,
|
|
"Unavailable low-light compensation is silently skipped");
|
|
Check(System.Runtime.InteropServices.Marshal.SizeOf(native.GetNestedType("CameraControlProperty",System.Reflection.BindingFlags.NonPublic)!)==40,
|
|
"Low-light control layout matches the Windows SDK");
|
|
Check(!new UvcCaptureOptions {LowLightCompensation=false}.IsDefault,
|
|
"Explicitly disabling low-light compensation is distinct from leaving the camera unchanged");
|
|
Check(System.Runtime.InteropServices.Marshal.SizeOf(native.GetNestedType("EvPayload",System.Reflection.BindingFlags.NonPublic)!)==56,
|
|
"Native EV payload layout matches the Windows SDK");
|
|
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");
|
|
Check(button.IsEffectivelyEnabled,"Runtime settings expose a camera configuration button next to the camera selector");
|
|
button.Command!.Execute(button.CommandParameter);
|
|
await Task.Delay(80);
|
|
var dialog=lifetime.Windows.OfType<SopHelper.VVMs.CameraSettings.CameraSettingsWindow>().Single();
|
|
try
|
|
{
|
|
var resolution=dialog.FindControl<ComboBox>("ResolutionPicker")!;
|
|
var rate=dialog.FindControl<ComboBox>("FrameRatePicker")!;
|
|
var format=dialog.FindControl<ComboBox>("FormatPicker")!;
|
|
var compensation=dialog.FindControl<ComboBox>("ExposureCompensationPicker")!;
|
|
var lowLight=dialog.FindControl<ComboBox>("LowLightCompensationPicker")!;
|
|
Check(dialog.Model.Resolutions.Any(r=>r.Width==4608)&&dialog.Model.FrameRates.Any(r=>r.Fps==30),"Resolution and frame rate dropdowns contain common presets including 16 MP and 30 fps");
|
|
resolution.SelectedItem=dialog.Model.Resolutions.Single(r=>r.Width==1920&&r.Height==1080);
|
|
rate.SelectedItem=dialog.Model.FrameRates.Single(r=>r.Fps==30);
|
|
format.SelectedItem="MJPG";
|
|
compensation.SelectedItem=dialog.Model.ExposureCompensations.Single(c=>c.Ev==-2d/3);
|
|
lowLight.SelectedItem=dialog.Model.LowLightCompensations.Single(p=>p.Enabled==false);
|
|
await Task.Delay(60);
|
|
Save(dialog,"camera-settings");
|
|
dialog.FindControl<Button>("SaveCameraSettingsButton")!.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
|
await Task.Delay(80);
|
|
var store=CameraSettingsStore.Current;
|
|
var settings=store.Load(sop.SelectedCamera!);
|
|
Check(settings.UsbCapture is {Width:1920,Height:1080,Fps:30,Format:"MJPG",LowLightCompensation:false,ExposureCompensationEv:var savedEv} && Math.Abs(savedEv!.Value+2d/3)<0.0001,"Camera dialog saves selected dropdown values independently of recipes");
|
|
var reopened=new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(sop.SelectedCamera!,store);
|
|
Check(reopened.SelectedResolution.Width==1920&&reopened.SelectedFrameRate.Fps==30&&reopened.SelectedFormat=="MJPG"&&reopened.SelectedLowLightCompensation.Enabled==false&&Math.Abs(reopened.SelectedExposureCompensation.Ev!.Value+2d/3)<0.0001,"Camera settings restore on reopening the dialog");
|
|
reopened.SelectedResolution=reopened.Resolutions[0];
|
|
Check(store.Load(sop.SelectedCamera!).UsbCapture.Width==1920,"Unsaved changes do not overwrite stored camera settings");
|
|
Check(store.Load(new CameraInfo{Index=9}).UsbCapture.IsDefault,"Each camera keeps its own independent settings");
|
|
var yaml=SopHelper.Engine.Sop.SopConfigLoader.ToYaml(new());
|
|
Check(!yaml.Contains("usb_capture")&&!yaml.Contains("exposure_time_us"),"Recipe YAML contains no camera settings");
|
|
using var probe=new FakeCamera();
|
|
await store.ApplyAsync(probe,sop.SelectedCamera!);
|
|
Check(probe.LastUsbOptions is {Width:1920,Height:1080,Fps:30,Format:"MJPG",LowLightCompensation:false,ExposureCompensationEv:var appliedEv} && Math.Abs(appliedEv!.Value+2d/3)<0.0001,"Acquisition receives settings from the per-camera store");
|
|
reopened.SelectedLowLightCompensation=reopened.LowLightCompensations.Single(p=>p.Enabled==true);
|
|
Check(reopened.Save()&&store.Load(sop.SelectedCamera!).UsbCapture.LowLightCompensation==true,
|
|
"Low-light compensation can also be enabled and saved");
|
|
reopened.SelectedLowLightCompensation=reopened.LowLightCompensations.Single(p=>p.Enabled is null);
|
|
Check(reopened.Save()&&store.Load(sop.SelectedCamera!).UsbCapture.LowLightCompensation is null,
|
|
"Leaving low-light compensation unchanged is preserved independently from on and off");
|
|
sop.IsRunning=true;await Task.Delay(20);
|
|
Check(!button.IsEffectivelyEnabled&&!sop.ConfigureCameraCommand.CanExecute(),"Camera configuration is disabled while running");
|
|
sop.IsRunning=false;
|
|
}
|
|
finally {dialog.Close();}
|
|
var recipeModel=new RecipeEditorViewModel();recipeModel.OnDialogOpened(new DialogParameters{{"new",true}});
|
|
var editor=new RecipeEditor {DataContext=recipeModel};
|
|
Check(editor.FindControl<TextBox>("CameraExposureInput") is null&&editor.FindControl<TextBox>("UsbWidthInput") is null,"Recipe editor no longer exposes camera settings");
|
|
await recipeModel.ShutdownAsync();
|
|
}
|
|
|
|
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 custom=Path.Combine(store.Root,"其它目录","结束图");
|
|
var blocked=Path.Combine(store.Root,"不能作为目录.txt");File.WriteAllText(blocked,"blocked");
|
|
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.Steps.Add(new()
|
|
{
|
|
Id=id,Name="步骤"+id,SaveCompletionImage=id!=2,
|
|
CompletionImageDirectory=id==3?custom:id==4?blocked:"",
|
|
Detection=new(){Method="time_elapsed",DurationMs=1,StableFrames=1}
|
|
});
|
|
var legacy=SopHelper.Engine.Sop.SopConfigLoader.Parse("sop:\n name: legacy\n steps:\n - id: 1\n name: first\n");
|
|
Check(legacy.Sop.Steps[0].SaveCompletionImage&&legacy.Sop.Steps[0].CompletionImageDirectory=="","Existing recipes default to saving completion images in their own recipe 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&&roundTrip.Sop.Steps[2].CompletionImageDirectory==custom,"Step image switches and custom Unicode directories survive editor and YAML round trips");
|
|
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
|
|
{
|
|
var toggle=editor.GetVisualDescendants().OfType<CheckBox>().Single(c=>c.Content?.ToString()=="保存结束图");
|
|
var directoryBox=editor.GetVisualDescendants().OfType<TextBox>().Single(t=>t.Name=="CompletionImageDirectoryBox");
|
|
Check(toggle.IsChecked==true&&string.IsNullOrEmpty(directoryBox.Text),"Step editor exposes image saving enabled by default with the recipe directory selected");
|
|
toggle.IsChecked=false;await Task.Delay(20);
|
|
Check(!editorVm.Recipe.SelectedStep!.SaveCompletionImage&&!directoryBox.IsEffectivelyEnabled,"Turning off image saving disables its directory controls");
|
|
toggle.IsChecked=true;editorVm.Recipe.SelectedStep=editorVm.Recipe.Steps[2];await Task.Delay(20);
|
|
Check(directoryBox.Text==custom,"Selecting another step restores its own custom image directory");
|
|
editor.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="恢复默认").RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
|
Check(editorVm.Recipe.SelectedStep.CompletionImageDirectory=="","Restore default clears the step's directory override");
|
|
directoryBox.Text=custom;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&&saved.Sop.Steps[2].CompletionImageDirectory==custom,"Saving the actual step editor persists per-step image settings");
|
|
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 receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
|
|
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++)
|
|
{
|
|
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(30);
|
|
}
|
|
await WaitForImages();
|
|
}
|
|
try
|
|
{
|
|
sop.IsRunning=true;engine.Start();
|
|
// A pending selection must not redirect the applied recipe's images.
|
|
sop.SelectedRecipe=selected;
|
|
await Round();
|
|
var defaults=Path.Combine(store.DirectoryFor(name),"completion-images");
|
|
var defaultFile=Directory.GetFiles(defaults,"*.png").Single();
|
|
var customFile=Directory.GetFiles(custom,"*.png").Single();
|
|
using(var image=Cv2.ImRead(defaultFile))Check(image.Width==64&&image.Height==48&&image.At<Vec3b>(0,0)==new Vec3b(30,60,90),"Default completion image is the exact judged frame and stays under the applied recipe");
|
|
using(var image=Cv2.ImRead(customFile))Check(image.At<Vec3b>(0,0)==new Vec3b(90,60,90),"Custom directory receives its step's exact completion frame after source disposal");
|
|
Check(defaultFile.Contains("step-1-")&&customFile.Contains("step-3-")&&sop.StepCards[1].HasCompletionImage,"Disabled image saving creates no file while retaining the on-screen completion image");
|
|
Check(engine.State==SopHelper.Engine.Sop.EngineState.Completed&&sop.Logs.Any(l=>l.Message.Contains("步骤 4 结束图保存失败")),"An unwritable image directory reports a warning without interrupting step completion");
|
|
engine.Reset();await Round();
|
|
Check(Directory.GetFiles(defaults,"*.png").Length==2&&Directory.GetFiles(custom,"*.png").Length==2,"A new round saves one new image per enabled step without overwriting prior images");
|
|
Check(File.Exists(defaultFile)&&File.Exists(customFile),"Reset preserves images already saved on disk");
|
|
}
|
|
finally
|
|
{
|
|
await WaitForImages();sop.IsRunning=false;sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
|
|
sop.Recipes.Remove(file);
|
|
}
|
|
}
|
|
|
|
private static async Task CheckVisionConfirmation(App app,SopPageViewModel sop)
|
|
{
|
|
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
|
|
{
|
|
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助手"}),"Recipe editor retains hand/AI controls and adds the video assistant without YOLO settings");
|
|
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");
|
|
padding.Value=200;await Task.Delay(20);
|
|
Check(editorVm.Recipe.ToConfig().Sop.Steps[0].AiConfirmation is {ImageMode:"hand",HandPadding:200,HandMinSize:320,HandMemoryMs:3000},"Editor persists dynamic hand crop settings");
|
|
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
|
|
{
|
|
Check(settingsView.GetVisualDescendants().OfType<ComboBox>().Count()==2&&settingsView.GetVisualDescendants().OfType<Slider>().Count()==1,"Runtime settings retain camera, recipe and stride while removing YOLO threshold");
|
|
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>();
|
|
Check(engine.Config.Sop.Model is null,"Pure hand/AI recipe skips YOLO loading");
|
|
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 saved=Directory.GetFiles(Path.Combine(store.DirectoryFor(name),"completion-images"),"*.png").Single();
|
|
using var evidence=Cv2.ImRead(saved);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(64,48)),"Agent test video opens");
|
|
for(var i=0;i<40;i++){using var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(i*4,60,90));writer.Write(frame);}
|
|
}
|
|
var client=new UiSopAgent();model.AgentClient=client;
|
|
model.AgentAutoVerify=false; // 此组只测草稿编辑;自动回测在专门的闭环测试中验证。
|
|
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 originalCount=model.Recipe.Steps.Count;
|
|
var configPath=store.ConfigPath("手部AI验证");var before=File.ReadAllBytes(configPath);
|
|
var tabs=editor.GetVisualDescendants().OfType<TabControl>().First();tabs.SelectedIndex=4;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");
|
|
model.ApplyAgentDraftCommand.Execute();
|
|
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");
|
|
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");
|
|
model.ApplyAgentDraftCommand.Execute();
|
|
Check(model.Recipe.Steps.Count==originalCount+1&&model.Recipe.Steps[originalCount].Id==appliedId&&model.Recipe.Steps[0].Name=="装配",
|
|
"Applying a chat revision updates owned steps without duplicates or changing existing recipe IDs");
|
|
Check(model.Recipe.Steps[originalCount].AiImageMode=="hand"&&model.Recipe.Steps[originalCount].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.Skip(originalCount).ToArray())model.Recipe.RemoveStep(step);
|
|
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 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 Task<bool> ConnectAsync(CameraInfo camera){IsConnected=true;ConnectionChanged?.Invoke(true);return Task.FromResult(true);}
|
|
public UvcCaptureOptions? LastUsbOptions {get;private set;}
|
|
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options){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(){Stop();IsConnected=false;ConnectionChanged?.Invoke(false);}public void Dispose()=>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),Steps=[
|
|
new(){Name="放入零件",Description="盒子里有零件",StartSeconds=0,EndSeconds=2,Region="work",EvidenceFrame=1},
|
|
new(){Name="取走零件",Description="盒子里没有零件",StartSeconds=2,EndSeconds=4,Region="work",EvidenceFrame=2}]});
|
|
}
|
|
}
|