将相机配置移出配方并增加独立下拉设置窗口

This commit is contained in:
tfarcraw 2026-11-18 15:06:08 +08:00
parent 8001129a2a
commit d9a3e69670
14 changed files with 267 additions and 105 deletions

View File

@ -20,7 +20,7 @@ pwsh -File tools/Start-HandAiD3.ps1
## 操作流程
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机曝光和 USB 采集参数在全局设置中。USB 可填写宽、高、目标 fps 和视频格式(MJPG / YUY2);留空使用驱动默认模式,宽高需成对填写。保存后重新启动采集生效,取图预览也使用这些参数。不支持的设置会报错;SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。目标 fps 不保证设备能达到,需根据相机支持的模式实测。
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率和视频格式使用下拉菜单选择,列表提供常用配置,不代表设备均支持;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。
3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。
4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。

View File

@ -0,0 +1,56 @@
using System.IO;
using System.Text.Json;
using SopHelper.Engine.Camera;
using SopHelper.Presentation;
namespace SopHelper.Models;
public sealed record CameraDeviceSettings
{
public UvcCaptureOptions UsbCapture { get; set; } = new();
public double? ExposureTimeUs { get; set; }
public void Validate()
{
UsbCapture.Validate();
if (ExposureTimeUs is { } exposure && (!double.IsFinite(exposure) || exposure <= 0))
throw new ArgumentException("曝光时间必须大于 0(微秒),或留空使用相机默认值");
}
}
/// <summary>按设备保存相机设置,独立于所有配方。</summary>
public sealed class CameraSettingsStore(string root)
{
public string FilePath => Path.Combine(root, "workspace", "camera-settings.json");
public static CameraSettingsStore Current => new(DesktopPlatform.WorkspaceRoot);
private static string Key(CameraInfo camera) => camera.Kind == CameraKind.Hikvision
? $"Hikvision:{camera.SerialNumber}" : $"Uvc:{camera.Index}";
private Dictionary<string, CameraDeviceSettings> Read() => File.Exists(FilePath)
? JsonSerializer.Deserialize<Dictionary<string, CameraDeviceSettings>>(File.ReadAllText(FilePath))
?? throw new InvalidDataException("相机设置文件内容为空")
: new();
public CameraDeviceSettings Load(CameraInfo camera) => Read().GetValueOrDefault(Key(camera)) ?? new();
public void Save(CameraInfo camera, CameraDeviceSettings settings)
{
settings.Validate();
var all = Read();
all[Key(camera)] = settings;
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
var temporary = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
File.WriteAllText(temporary, JsonSerializer.Serialize(all, new JsonSerializerOptions { WriteIndented = true }));
File.Move(temporary, FilePath, true);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
}
public async Task<string> ApplyAsync(ICameraService service, CameraInfo camera)
{
var settings = Load(camera);
settings.Validate();
var description = camera.Kind == CameraKind.Uvc
? await service.ConfigureUvcAsync(settings.UsbCapture) : "";
if (settings.ExposureTimeUs is { } exposure) await service.SetExposureTimeAsync(exposure);
return description;
}
}

View File

@ -180,6 +180,8 @@ public sealed partial class CameraViewModel : BindableBase
Status = "正在连接 " + selected.Name;
if (!await _camera.ConnectAsync(selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用");
if (_closing) return;
try { await SopHelper.Models.CameraSettingsStore.Current.ApplyAsync(_camera, selected); }
catch { await Task.Run(_camera.Disconnect); throw; }
if (!await _camera.StartAsync())
{
await Task.Run(_camera.Disconnect);

View File

@ -0,0 +1,75 @@
using System.Collections.ObjectModel;
using Prism.Mvvm;
using SopHelper.Engine.Camera;
using SopHelper.Models;
namespace SopHelper.VVMs.CameraSettings;
public sealed record ResolutionPreset(int? Width, int? Height)
{
public override string ToString() => Width is null ? "驱动默认" : $"{Width} × {Height}";
}
public sealed record FrameRatePreset(double? Fps)
{
public override string ToString() => Fps is null ? "驱动默认" : $"{Fps:0.##} fps";
}
public sealed class CameraSettingsViewModel : BindableBase
{
private readonly CameraInfo _camera;
private readonly CameraSettingsStore _store;
private string _error = "";
public string CameraName => _camera.Name;
public bool IsUsb => _camera.Kind == CameraKind.Uvc;
public bool IsIndustrial => !IsUsb;
public ObservableCollection<ResolutionPreset> Resolutions { get; } = new([
new(null,null), new(640,480), new(800,600), new(1280,720), new(1280,960),
new(1920,1080), new(1920,1200), new(2560,1440), new(2592,1944),
new(3264,2448), new(3840,2160), new(4096,2160), new(4608,3456), new(4656,3496)]);
public ObservableCollection<FrameRatePreset> FrameRates { get; } = new([
new(null), new(5), new(10), new(15), new(20), new(24), new(25), new(30), new(50), new(60), new(120)]);
public string[] Formats { get; } = ["驱动默认", "MJPG", "YUY2"];
public ResolutionPreset SelectedResolution { get; set; }
public FrameRatePreset SelectedFrameRate { get; set; }
public string SelectedFormat { get; set; } = "驱动默认";
public double? ExposureTimeUs { get; set; }
public string Error { get => _error; private set => SetProperty(ref _error, value); }
public bool CanSave { get; private set; } = true;
public CameraSettingsViewModel(CameraInfo camera, CameraSettingsStore store)
{
_camera = camera; _store = store;
SelectedResolution = Resolutions[0]; SelectedFrameRate = FrameRates[0];
try
{
var settings = store.Load(camera);
settings.Validate();
var resolution = new ResolutionPreset(settings.UsbCapture.Width, settings.UsbCapture.Height);
if (!Resolutions.Contains(resolution)) Resolutions.Add(resolution);
SelectedResolution = Resolutions.First(r => r == resolution);
var rate = new FrameRatePreset(settings.UsbCapture.Fps);
if (!FrameRates.Contains(rate)) FrameRates.Add(rate);
SelectedFrameRate = FrameRates.First(r => r == rate);
SelectedFormat = string.IsNullOrWhiteSpace(settings.UsbCapture.Format) ? Formats[0] : settings.UsbCapture.Format.Trim().ToUpperInvariant();
ExposureTimeUs = settings.ExposureTimeUs;
}
catch (Exception ex) { Error = "读取相机设置失败:" + ex.Message; CanSave = false; }
}
public bool Save()
{
if (!CanSave) return false;
try
{
_store.Save(_camera, new CameraDeviceSettings
{
UsbCapture = IsUsb ? new UvcCaptureOptions
{
Width = SelectedResolution.Width, Height = SelectedResolution.Height,
Fps = SelectedFrameRate.Fps, Format = SelectedFormat == Formats[0] ? null : SelectedFormat
} : new(),
ExposureTimeUs = IsIndustrial ? ExposureTimeUs : null
});
Error = ""; return true;
}
catch (Exception ex) { Error = "保存相机设置失败:" + ex.Message; return false; }
}
}

View File

@ -0,0 +1,39 @@
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SopHelper.VVMs.CameraSettings.CameraSettingsWindow" Title="相机配置"
Width="520" Height="480" MinWidth="440" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner">
<Grid Margin="24" RowDefinitions="Auto,*,Auto">
<StackPanel Spacing="8">
<TextBlock Text="相机配置" Classes="Title" />
<TextBlock Text="{Binding CameraName}" TextWrapping="Wrap" />
</StackPanel>
<ScrollViewer Grid.Row="1" Margin="0,20,0,16" HorizontalScrollBarVisibility="Disabled">
<StackPanel Spacing="14">
<StackPanel IsVisible="{Binding IsUsb}" Spacing="12">
<Grid ColumnDefinitions="100,*">
<TextBlock Text="分辨率" VerticalAlignment="Center" />
<ComboBox x:Name="ResolutionPicker" Grid.Column="1" ItemsSource="{Binding Resolutions}" SelectedItem="{Binding SelectedResolution, Mode=TwoWay}" HorizontalAlignment="Stretch" />
</Grid>
<Grid ColumnDefinitions="100,*">
<TextBlock Text="目标帧率" VerticalAlignment="Center" />
<ComboBox x:Name="FrameRatePicker" Grid.Column="1" ItemsSource="{Binding FrameRates}" SelectedItem="{Binding SelectedFrameRate, Mode=TwoWay}" HorizontalAlignment="Stretch" />
</Grid>
<Grid ColumnDefinitions="100,*">
<TextBlock Text="视频格式" VerticalAlignment="Center" />
<ComboBox x:Name="FormatPicker" Grid.Column="1" ItemsSource="{Binding Formats}" SelectedItem="{Binding SelectedFormat, Mode=TwoWay}" HorizontalAlignment="Stretch" />
</Grid>
<TextBlock Text="列表为常用配置,不代表当前相机均支持。选择“驱动默认”可保留默认模式;实际协商结果见运行日志。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
</StackPanel>
<StackPanel IsVisible="{Binding IsIndustrial}" Spacing="8">
<TextBlock Text="曝光时间(μs)" />
<TextBox x:Name="ExposureInput" Text="{Binding ExposureTimeUs, Mode=TwoWay}" PlaceholderText="留空使用相机默认值" />
</StackPanel>
<TextBlock Text="设置按相机独立保存,切换配方不会改变;下次开启采集、取图或录像预览时生效。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
<TextBlock Text="{Binding Error}" Foreground="{StaticResource Ng}" TextWrapping="Wrap" />
</StackPanel>
</ScrollViewer>
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="10">
<Button Content="取消" Click="Cancel" />
<Button x:Name="SaveCameraSettingsButton" Content="保存" Click="Save" IsEnabled="{Binding CanSave}" />
</StackPanel>
</Grid>
</Window>

View File

@ -0,0 +1,15 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
namespace SopHelper.VVMs.CameraSettings;
public partial class CameraSettingsWindow : Window
{
public CameraSettingsViewModel Model { get; }
public CameraSettingsWindow(CameraSettingsViewModel model)
{
InitializeComponent(); Model = model; DataContext = model;
}
private void Save(object? sender, RoutedEventArgs e) { if (Model.Save()) Close(true); }
private void Cancel(object? sender, RoutedEventArgs e) => Close(false);
}

View File

@ -525,16 +525,6 @@ public class RecipeSettingsNode : EditorNode
private bool _autoResetOnComplete = true;
private int _resetDelaySec = 1;
private int _frameStride = 1;
private double? _exposureTimeUs;
public SopHelper.Engine.Camera.UvcCaptureOptions UsbCapture { get; set; } = new();
public double? ExposureTimeUs
{
get => _exposureTimeUs;
set => SetProperty(ref _exposureTimeUs, value);
}
/// <summary>全局置信度阈值</summary>
public float ConfidenceThreshold
{
@ -587,8 +577,6 @@ public class RecipeSettingsNode : EditorNode
/// <summary>读入</summary>
public void CopyFrom(SopSettings from)
{
UsbCapture = from.UsbCapture with { };
ExposureTimeUs = from.ExposureTimeUs;
ConfidenceThreshold = from.ConfidenceThreshold;
StableFrames = from.StableFrames;
PositionTolerance = from.PositionTolerance;
@ -601,8 +589,6 @@ public class RecipeSettingsNode : EditorNode
/// <summary>写出</summary>
public void CopyTo(SopSettings to)
{
to.UsbCapture = UsbCapture with { };
to.ExposureTimeUs = ExposureTimeUs;
to.ConfidenceThreshold = ConfidenceThreshold;
to.StableFrames = StableFrames;
to.PositionTolerance = PositionTolerance;

View File

@ -370,21 +370,6 @@
</TabItem>
<TabItem Header="全局设置">
<StackPanel Margin="10" DataContext="{Binding Recipe.Settings}">
<WrapPanel Margin="0,0,0,8">
<TextBlock Text="USB 宽" VerticalAlignment="Center" Margin="0,0,8,0" />
<TextBox x:Name="UsbWidthInput" Width="80" Text="{Binding UsbCapture.Width, Mode=TwoWay}" />
<TextBlock Text="高" VerticalAlignment="Center" Margin="8,0" />
<TextBox x:Name="UsbHeightInput" Width="80" Text="{Binding UsbCapture.Height, Mode=TwoWay}" />
<TextBlock Text="目标 fps" VerticalAlignment="Center" Margin="8,0" />
<TextBox x:Name="UsbFpsInput" Width="70" Text="{Binding UsbCapture.Fps, Mode=TwoWay}" />
<TextBlock Text="格式" VerticalAlignment="Center" Margin="8,0" />
<TextBox x:Name="UsbFormatInput" Width="80" Text="{Binding UsbCapture.Format, Mode=TwoWay}" PlaceholderText="默认" ToolTip.Tip="MJPG / YUY2;留空使用驱动默认格式" />
</WrapPanel>
<TextBlock Text="USB 参数留空使用驱动默认模式;保存后重新启动采集生效。实际协商参数见 SOP 日志;渲染 fps 不等于相机帧率。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,10" />
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
<TextBlock Text="相机曝光(μs)" VerticalAlignment="Center" Margin="0,0,8,0" />
<TextBox x:Name="CameraExposureInput" Width="120" Text="{Binding ExposureTimeUs, Mode=TwoWay}" ToolTip.Tip="留空保留相机当前曝光设置" />
</StackPanel>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />

View File

@ -121,8 +121,6 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
_isNew = parameters.GetValue<bool>("new");
_onSaved = parameters.GetValue<Action<string>>("onSaved");
SaveStatus = "";
try { Recipe.Settings.UsbCapture.Validate(); }
catch (ArgumentException ex) { Warnings.Add(ex.Message); return; }
_camera = parameters.GetValue<ICameraService>("cameraService");
_cameraInfo = parameters.GetValue<CameraInfo>("cameraInfo");
_selectedCameraProvider = parameters.GetValue<Func<CameraInfo?>>("selectedCameraProvider") ?? (() => _cameraInfo);
@ -237,14 +235,7 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
try
{
if (!await camera.ConnectAsync(_cameraInfo)) throw new InvalidOperationException("连接相机失败,请查看 SOP 页日志");
if (_cameraInfo.Kind == CameraKind.Uvc)
await camera.ConfigureUvcAsync(Recipe.Settings.UsbCapture);
if (Recipe.Settings.ExposureTimeUs is { } exposure)
{
if (!double.IsFinite(exposure) || exposure <= 0)
throw new InvalidOperationException("相机曝光必须大于 0(微秒),或留空保留相机设置");
await camera.SetExposureTimeAsync(exposure);
}
await SopHelper.Models.CameraSettingsStore.Current.ApplyAsync(camera, _cameraInfo);
camera.FrameArrived += Receive;
if (!await camera.StartAsync()) throw new InvalidOperationException("启动采集失败");
PreviewImage = await ready.Task.WaitAsync(TimeSpan.FromSeconds(5));
@ -263,13 +254,6 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
private void Save()
{
SaveStatus = "";
try { Recipe.Settings.UsbCapture.Validate(); }
catch (ArgumentException ex) { Warnings.Add(ex.Message); return; }
if (Recipe.Settings.ExposureTimeUs is { } exposure && (!double.IsFinite(exposure) || exposure <= 0))
{
Warnings.Add("相机曝光必须大于 0(微秒),或留空保留相机设置");
return;
}
if (RecipeWorkspace.GetNameError(Recipe.Name) is { } nameError)
{
SaveStatus = nameError;
@ -318,8 +302,6 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
private void RefreshWarnings()
{
SaveStatus = "";
try { Recipe.Settings.UsbCapture.Validate(); }
catch (ArgumentException ex) { Warnings.Add(ex.Message); return; }
RaisePropertyChanged(nameof(NameValidationMessage));
RaisePropertyChanged(nameof(FileNameText));
SaveCommand.RaiseCanExecuteChanged();

View File

@ -11,6 +11,7 @@
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="相机" Width="40" />
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" ItemsSource="{Binding Cameras}" IsEnabled="{Binding CanSelectCamera}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" ToolTip.Tip="支持 UVC 和海康 GigE/USB 工业相机">
@ -20,7 +21,8 @@
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Grid.Column="2" Content="刷新" Margin="6,0,0,0" Padding="10,4" Command="{Binding RefreshCamerasCommand}" />
<Button x:Name="ConfigureCameraButton" Grid.Column="2" Content="配置" Margin="6,0,0,0" Padding="10,4" Command="{Binding ConfigureCameraCommand}" />
<Button Grid.Column="3" Content="刷新" Margin="6,0,0,0" Padding="10,4" Command="{Binding RefreshCamerasCommand}" />
</Grid>
<Grid Margin="0,8,0,0">
<Grid.ColumnDefinitions>

View File

@ -133,6 +133,7 @@ public class SopPageViewModel : ViewModelBase
LoadRecipes();
// 命令接线(DelegateCommand 的可用条件都挂在这里)
ConfigureCameraCommand = new DelegateCommand(async () => await ConfigureCameraAsync(), () => CanSelectCamera && SelectedCamera is not null && !IsConnected);
RefreshCamerasCommand = new DelegateCommand(async () => await RefreshCamerasAsync(), () => CanSelectCamera);
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
@ -309,6 +310,9 @@ public class SopPageViewModel : ViewModelBase
set { SetProperty(ref _frameStride, value); }
}
/// <summary>打开所选相机的独立配置窗口</summary>
public DelegateCommand ConfigureCameraCommand { get; private set; } = null!;
/// <summary>刷新相机列表</summary>
public DelegateCommand RefreshCamerasCommand { get; private set; } = null!;
@ -356,6 +360,7 @@ public class SopPageViewModel : ViewModelBase
private void RaiseCommands()
{
// 构造函数里 LoadRecipes() 会先设 SelectedRecipe,那时命令还没创建,必须空安全
ConfigureCameraCommand?.RaiseCanExecuteChanged();
RefreshCamerasCommand?.RaiseCanExecuteChanged();
StartStopCommand?.RaiseCanExecuteChanged();
TogglePauseCommand?.RaiseCanExecuteChanged();
@ -605,6 +610,22 @@ public class SopPageViewModel : ViewModelBase
_dialogs.ShowDialog(EditorDialogName, parameters, _ => { });
}
private async Task ConfigureCameraAsync()
{
if (!CanSelectCamera || SelectedCamera is null || IsConnected) return;
var camera = SelectedCamera;
SetCameraBusy(true);
try
{
var model = new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(camera, SopHelper.Models.CameraSettingsStore.Current);
var dialog = new SopHelper.VVMs.CameraSettings.CameraSettingsWindow(model);
if (await dialog.ShowDialog<bool>(DesktopPlatform.Owner))
StatusText = "相机配置已保存,下次开启采集生效";
}
catch (Exception ex) { Log("error", "打开相机配置失败:" + ex.Message); }
finally { SetCameraBusy(false); }
}
private void LoadLastCamera()
{
try
@ -712,33 +733,17 @@ public class SopPageViewModel : ViewModelBase
ApplyRecipe();
if (SelectedCamera.Kind == CameraKind.Uvc)
try
{
try { Log("info", await _camera.ConfigureUvcAsync(_engine.Config.Sop.Settings.UsbCapture)); }
catch (Exception ex)
{
Log("error", "设置 USB 采集参数失败:" + ex.Message);
await Task.Run(_camera.Disconnect);
StatusText = "设置 USB 采集参数失败";
return;
}
var mode = await SopHelper.Models.CameraSettingsStore.Current.ApplyAsync(_camera, SelectedCamera);
if (!string.IsNullOrEmpty(mode)) Log("info", mode);
}
if (_engine.Config.Sop.Settings.ExposureTimeUs is { } exposure)
catch (Exception ex)
{
try
{
if (!double.IsFinite(exposure) || exposure <= 0)
throw new InvalidOperationException("相机曝光必须大于 0(微秒),或留空保留相机设置");
await _camera.SetExposureTimeAsync(exposure);
}
catch (Exception ex)
{
Log("error", "设置相机曝光失败:" + ex.Message);
await Task.Run(_camera.Disconnect);
StatusText = "设置相机曝光失败";
return;
}
Log("error", "设置相机参数失败:" + ex.Message);
await Task.Run(_camera.Disconnect);
StatusText = "设置相机参数失败";
return;
}
// 抽帧从界面参数覆盖配方默认值

View File

@ -7,7 +7,7 @@ public sealed record UvcCaptureOptions
public int? Height { get; set; }
public double? Fps { get; set; }
public string? Format { get; set; }
[YamlDotNet.Serialization.YamlIgnore]
[YamlDotNet.Serialization.YamlIgnore, System.Text.Json.Serialization.JsonIgnore]
public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format);
public void Validate()

View File

@ -51,12 +51,6 @@ public class SopBody
/// </summary>
public class SopSettings
{
public SopHelper.Engine.Camera.UvcCaptureOptions UsbCapture { get; set; } = new();
/// <summary>手动相机曝光(微秒);空值保留相机当前设置。</summary>
[YamlDotNet.Serialization.YamlMember(DefaultValuesHandling = YamlDotNet.Serialization.DefaultValuesHandling.OmitNull)]
public double? ExposureTimeUs { get; set; }
/// <summary>全局置信度阈值</summary>
public float ConfidenceThreshold { get; set; } = 0.6f;

View File

@ -98,7 +98,7 @@ internal static class Smoke
Console.WriteLine("Models: "+string.Join(", ",model.AgentModels));
await model.ShutdownAsync();dialog.Close();_exit=0;return;
}
if(Environment.GetCommandLineArgs().Contains("--usb-capture-only")) { await CheckUsbCapture(); _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>();
@ -571,39 +571,58 @@ internal static class Smoke
finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
}
private static async Task CheckUsbCapture()
private static async Task CheckUsbCapture(App app)
{
var legacy=SopHelper.Engine.Sop.SopConfigLoader.Parse("sop:\n name: legacy\n");
Check(legacy.Sop.Settings.UsbCapture.IsDefault,"Existing recipes preserve default USB camera negotiation");
foreach(var invalid in new UvcCaptureOptions[] {new(){Width=1920},new(){Width=0,Height=1080},new(){Fps=double.NaN},new(){Fps=-1},new(){Format="bad"}})
{
var rejected=false;
try {invalid.Validate();} catch(ArgumentException){rejected=true;}
Check(rejected,"Invalid USB capture request is rejected before reaching the driver");
}
var model=new RecipeEditorViewModel();
model.OnDialogOpened(new DialogParameters{{"new",true}});
var editor=new RecipeEditor {DataContext=model};
var dialog=new Window {Content=editor,Width=1040,Height=760};dialog.Show();
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
{
editor.GetVisualDescendants().OfType<TabControl>().First().SelectedIndex=2;
await Task.Delay(80);
editor.FindControl<TextBox>("UsbWidthInput")!.Text="1920";
editor.FindControl<TextBox>("UsbHeightInput")!.Text="1080";
editor.FindControl<TextBox>("UsbFpsInput")!.Text="30";
editor.FindControl<TextBox>("UsbFormatInput")!.Text="MJPG";
var resolution=dialog.FindControl<ComboBox>("ResolutionPicker")!;
var rate=dialog.FindControl<ComboBox>("FrameRatePicker")!;
var format=dialog.FindControl<ComboBox>("FormatPicker")!;
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";
await Task.Delay(60);
var config=model.Recipe.ToConfig();
config.Sop.Settings.UsbCapture.Validate();
var yaml=SopHelper.Engine.Sop.SopConfigLoader.ToYaml(config);
var restored=SopHelper.Engine.Sop.SopConfigLoader.Parse(yaml);
Check(restored.Sop.Settings.UsbCapture is {Width:1920,Height:1080,Fps:30,Format:"MJPG"},"USB inputs survive editor mapping and YAML save/load");
Check(!yaml.Contains("is_default"),"Computed USB state is excluded from recipe YAML");
model.Recipe.Settings.UsbCapture.Width=1280;
Check(config.Sop.Settings.UsbCapture.Width==1920,"Editing USB inputs does not mutate the applied configuration");
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"},"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","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"},"Acquisition receives settings from the per-camera store");
sop.IsRunning=true;await Task.Delay(20);
Check(!button.IsEffectivelyEnabled&&!sop.ConfigureCameraCommand.CanExecute(),"Camera configuration is disabled while running");
sop.IsRunning=false;
}
finally {await model.ShutdownAsync();dialog.Close();}
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)
@ -726,7 +745,7 @@ internal static class Smoke
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 not null,"Camera exposure remains available in global settings");
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");
@ -918,6 +937,8 @@ internal sealed class FakeCamera : ICameraService
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;