diff --git a/README.md b/README.md
index 7e39676..4d276d1 100644
--- a/README.md
+++ b/README.md
@@ -20,7 +20,7 @@ pwsh -File tools/Start-HandAiD3.ps1
## 操作流程
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。
-2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机曝光在全局设置中。
+2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机曝光和 USB 采集参数在全局设置中。USB 可填写宽、高、目标 fps 和视频格式(MJPG / YUY2);留空使用驱动默认模式,宽高需成对填写。保存后重新启动采集生效,取图预览也使用这些参数。不支持的设置会报错;SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。目标 fps 不保证设备能达到,需根据相机支持的模式实测。
3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。
4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
index 7c65636..8c998f1 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
@@ -526,6 +526,7 @@ public class RecipeSettingsNode : EditorNode
private int _resetDelaySec = 1;
private int _frameStride = 1;
private double? _exposureTimeUs;
+ public SopHelper.Engine.Camera.UvcCaptureOptions UsbCapture { get; set; } = new();
public double? ExposureTimeUs
{
@@ -586,6 +587,7 @@ public class RecipeSettingsNode : EditorNode
/// 读入
public void CopyFrom(SopSettings from)
{
+ UsbCapture = from.UsbCapture with { };
ExposureTimeUs = from.ExposureTimeUs;
ConfidenceThreshold = from.ConfidenceThreshold;
StableFrames = from.StableFrames;
@@ -599,6 +601,7 @@ public class RecipeSettingsNode : EditorNode
/// 写出
public void CopyTo(SopSettings to)
{
+ to.UsbCapture = UsbCapture with { };
to.ExposureTimeUs = ExposureTimeUs;
to.ConfidenceThreshold = ConfidenceThreshold;
to.StableFrames = StableFrames;
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
index bc3d411..7231f3b 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
@@ -370,6 +370,17 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
index 857e115..5906039 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
@@ -121,6 +121,8 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
_isNew = parameters.GetValue("new");
_onSaved = parameters.GetValue>("onSaved");
SaveStatus = "";
+ try { Recipe.Settings.UsbCapture.Validate(); }
+ catch (ArgumentException ex) { Warnings.Add(ex.Message); return; }
_camera = parameters.GetValue("cameraService");
_cameraInfo = parameters.GetValue("cameraInfo");
_selectedCameraProvider = parameters.GetValue>("selectedCameraProvider") ?? (() => _cameraInfo);
@@ -235,6 +237,8 @@ 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)
@@ -259,6 +263,8 @@ 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(微秒),或留空保留相机设置");
@@ -312,6 +318,8 @@ 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();
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index 21f9b96..a98f4d7 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -712,6 +712,18 @@ public class SopPageViewModel : ViewModelBase
ApplyRecipe();
+ if (SelectedCamera.Kind == CameraKind.Uvc)
+ {
+ 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;
+ }
+ }
+
if (_engine.Config.Sop.Settings.ExposureTimeUs is { } exposure)
{
try
@@ -924,7 +936,8 @@ public class SopPageViewModel : ViewModelBase
// 按真实经过的时间统计成功发布的预览帧。
if (_fpsClock.Elapsed.TotalSeconds >= 0.5)
{
- FpsText = $"{(_frameCount - _lastTickCount) / _fpsClock.Elapsed.TotalSeconds:F1} fps(渲染)";
+ FpsText = (_camera.MeasuredCaptureFps is { } captureFps ? $"采集 {captureFps:F1} / " : "")
+ + $"渲染 {(_frameCount - _lastTickCount) / _fpsClock.Elapsed.TotalSeconds:F1} fps";
_lastTickCount = _frameCount;
_fpsClock.Restart();
}
diff --git a/src/SopHelper.CrossPlatform.Engine/Camera/CameraService.cs b/src/SopHelper.CrossPlatform.Engine/Camera/CameraService.cs
index 650223b..70abf6d 100644
--- a/src/SopHelper.CrossPlatform.Engine/Camera/CameraService.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Camera/CameraService.cs
@@ -21,6 +21,7 @@ public sealed class CameraService : ICameraService
public bool IsConnected => _active?.IsConnected == true;
public bool IsGrabbing => _active?.IsGrabbing == true;
+ public double? MeasuredCaptureFps => _active?.MeasuredCaptureFps;
public event Action? FrameArrived;
public event Action? ConnectionChanged;
public event Action? Error;
@@ -64,6 +65,18 @@ public sealed class CameraService : ICameraService
finally { _operations.Release(); }
}
+ public async Task ConfigureUvcAsync(UvcCaptureOptions options)
+ {
+ await _operations.WaitAsync().ConfigureAwait(false);
+ try
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ if (_active is null || !_active.IsConnected) throw new InvalidOperationException("请先连接相机");
+ return await _active.ConfigureUvcAsync(options).ConfigureAwait(false);
+ }
+ finally { _operations.Release(); }
+ }
+
public async Task StartAsync()
{
await _operations.WaitAsync().ConfigureAwait(false);
diff --git a/src/SopHelper.CrossPlatform.Engine/Camera/ICameraService.cs b/src/SopHelper.CrossPlatform.Engine/Camera/ICameraService.cs
index f2c2489..096c810 100644
--- a/src/SopHelper.CrossPlatform.Engine/Camera/ICameraService.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Camera/ICameraService.cs
@@ -55,6 +55,9 @@ public interface ICameraService : IDisposable
/// 是否正在采集
bool IsGrabbing { get; }
+ /// 采集循环实测帧率;尚未测得或后端不支持时为空。
+ double? MeasuredCaptureFps => null;
+
/// 新帧(在采集线程上触发,消费方用完不得保留 Mat)
event Action? FrameArrived;
@@ -74,6 +77,11 @@ public interface ICameraService : IDisposable
Task SetExposureTimeAsync(double microseconds) =>
Task.FromException(new NotSupportedException("当前相机不支持以微秒设置曝光,请将配方的相机曝光留空"));
+ /// 连接后、采集前配置 USB 模式,返回驱动回读参数。
+ Task ConfigureUvcAsync(UvcCaptureOptions options) => options.IsDefault
+ ? Task.FromResult("")
+ : Task.FromException(new NotSupportedException("当前相机不支持 USB 采集参数"));
+
/// 开始采集
Task StartAsync();
diff --git a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs
index db401d5..77ae1a8 100644
--- a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs
@@ -40,6 +40,7 @@ public class UvcCameraService : ICameraService
/// 实测帧率(每 2 秒刷新一次)
public double ActualFps { get; private set; }
+ public double? MeasuredCaptureFps => IsGrabbing && ActualFps > 0 ? ActualFps : null;
///
public Task> EnumerateAsync()
@@ -122,6 +123,43 @@ public class UvcCameraService : ICameraService
});
}
+ public Task ConfigureUvcAsync(UvcCaptureOptions options) => Task.Run(() =>
+ {
+ options.Validate();
+ lock (DshowLock)
+ lock (_captureLock)
+ {
+ var capture = _capture ?? throw new InvalidOperationException("请先连接相机");
+ if (IsGrabbing) throw new InvalidOperationException("请停止采集后再设置 USB 参数");
+ void Set(VideoCaptureProperties property, double value, string label)
+ {
+ if (!capture.Set(property, value))
+ throw new InvalidOperationException($"驱动不支持 USB {label},请更换参数或留空使用默认模式");
+ }
+ // 先协商传输格式,再协商分辨率和帧率。
+ if (!string.IsNullOrWhiteSpace(options.Format))
+ {
+ var format = options.Format.Trim().ToUpperInvariant();
+ Set(VideoCaptureProperties.FourCC, VideoWriter.FourCC(format[0], format[1], format[2], format[3]), "视频格式 " + format);
+ }
+ if (options.Width is { } width) Set(VideoCaptureProperties.FrameWidth, width, "宽度");
+ if (options.Height is { } height) Set(VideoCaptureProperties.FrameHeight, height, "高度");
+ if (options.Fps is { } fps) Set(VideoCaptureProperties.Fps, fps, "目标帧率");
+ var actualWidth = capture.Get(VideoCaptureProperties.FrameWidth);
+ var actualHeight = capture.Get(VideoCaptureProperties.FrameHeight);
+ var actualFps = capture.Get(VideoCaptureProperties.Fps);
+ var code = (int)capture.Get(VideoCaptureProperties.FourCC);
+ var actualFormat = new string(Enumerable.Range(0, 4).Select(i => (char)((code >> (8 * i)) & 255)).ToArray()).Trim('\0', ' ');
+ var mismatch = options.Width is { } w && Math.Abs(actualWidth - w) > 0.5
+ || options.Height is { } h && Math.Abs(actualHeight - h) > 0.5
+ || options.Fps is { } f && Math.Abs(actualFps - f) > 0.5
+ || !string.IsNullOrWhiteSpace(options.Format) && actualFormat != options.Format.Trim().ToUpperInvariant();
+ ActualFps = 0;
+ return $"USB 驱动回读:{actualWidth:F0}×{actualHeight:F0},{actualFps:F1} fps,格式 {actualFormat}(非实测帧率)"
+ + (mismatch ? ";与请求不一致,请调整到相机支持的模式" : "");
+ }
+ });
+
///
public Task StartAsync()
{
@@ -137,6 +175,7 @@ public class UvcCameraService : ICameraService
if (IsGrabbing) return true;
+ ActualFps = 0;
_cts = new CancellationTokenSource();
IsGrabbing = true;
_grabTask = Task.Run(() => GrabLoop(capture, _cts.Token));
diff --git a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs
new file mode 100644
index 0000000..52db733
--- /dev/null
+++ b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs
@@ -0,0 +1,22 @@
+namespace SopHelper.Engine.Camera;
+
+/// USB 采集请求;空值使用驱动默认模式。
+public sealed record UvcCaptureOptions
+{
+ public int? Width { get; set; }
+ public int? Height { get; set; }
+ public double? Fps { get; set; }
+ public string? Format { get; set; }
+ [YamlDotNet.Serialization.YamlIgnore]
+ public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format);
+
+ public void Validate()
+ {
+ if ((Width is null) != (Height is null) || Width is <= 0 || Height is <= 0)
+ throw new ArgumentException("USB 分辨率的宽、高必须同时填写正整数,或同时留空");
+ if (Fps is { } fps && (!double.IsFinite(fps) || fps <= 0))
+ throw new ArgumentException("USB 目标帧率必须是大于 0 的有限数值,或留空");
+ if (!string.IsNullOrWhiteSpace(Format) && Format.Trim().ToUpperInvariant() is not ("MJPG" or "YUY2"))
+ throw new ArgumentException("USB 视频格式请填写 MJPG、YUY2,或留空使用默认格式");
+ }
+}
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
index fe83e86..c87572b 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
@@ -51,6 +51,8 @@ public class SopBody
///
public class SopSettings
{
+ public SopHelper.Engine.Camera.UvcCaptureOptions UsbCapture { get; set; } = new();
+
/// 手动相机曝光(微秒);空值保留相机当前设置。
[YamlDotNet.Serialization.YamlMember(DefaultValuesHandling = YamlDotNet.Serialization.DefaultValuesHandling.OmitNull)]
public double? ExposureTimeUs { get; set; }
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index 21fe695..ef421f3 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -98,6 +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; }
CheckCameraPreferences(app);
CheckRecipePreferences(app);
var navigation=app.Container.Resolve();
@@ -570,6 +571,41 @@ internal static class Smoke
finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
}
+ private static async Task CheckUsbCapture()
+ {
+ 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();
+ try
+ {
+ editor.GetVisualDescendants().OfType().First().SelectedIndex=2;
+ await Task.Delay(80);
+ editor.FindControl("UsbWidthInput")!.Text="1920";
+ editor.FindControl("UsbHeightInput")!.Text="1080";
+ editor.FindControl("UsbFpsInput")!.Text="30";
+ editor.FindControl("UsbFormatInput")!.Text="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");
+ }
+ finally {await model.ShutdownAsync();dialog.Close();}
+ }
+
private static async Task CheckCompletionImageSaving(App app,SopPageViewModel sop)
{
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);