复用驱动属性设置后的相机连接以避免启动时重置
This commit is contained in:
parent
281c5a0af4
commit
bd9e4957f1
@ -20,7 +20,7 @@ pwsh -File tools/Start-HandAiD3.ps1
|
||||
## 操作流程
|
||||
|
||||
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。
|
||||
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和采集方式使用下拉菜单选择;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。要尝试驱动原生图像控制,在相机“配置”窗口中直接点击“驱动属性”,无需先保存或启动采集;程序用临时 DirectShow 连接打开属性页,页面关闭后释放设备,采集方式切换为 DirectShow,点击“保存”保留该选择。原生页面的项目和保存行为由驱动决定,程序不再模拟 EV 补偿或低亮度补偿开关,也不应用旧配置中的这两个字段。原生属性页不可用时静默跳过;SOP 日志显示驱动回读采集模式,状态栏分别显示 USB 实测采集和渲染 fps。
|
||||
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和采集方式使用下拉菜单选择;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。要尝试驱动原生图像控制,先在相机“配置”窗口中选定分辨率、帧率及视频格式,再点击“驱动属性”,无需先启动 SOP。属性页使用主相机服务,先应用视频模式再显示驱动页面,关闭页面后保留相机连接;点击“保存”后正式采集复用同一连接及视频模式,不重复设置分辨率、帧率或重建图。取消配置会释放本次驱动会话;设备切换、视频参数改变或停止并断开后仍需重新连接,驱动是否跨连接记住图像选项由驱动决定。原生页面的项目和保存行为由驱动决定,程序不再模拟 EV 补偿或低亮度补偿开关,也不应用旧配置中的这两个字段。原生属性页不可用时静默跳过;SOP 日志显示驱动回读采集模式,状态栏分别显示 USB 实测采集和渲染 fps。
|
||||
3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。
|
||||
4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。
|
||||
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。
|
||||
|
||||
@ -24,6 +24,8 @@ public sealed class CameraSettingsViewModel : BindableBase
|
||||
private readonly CameraSettingsStore _store;
|
||||
private string _error = "";
|
||||
private readonly Func<ICameraService> _driverCameraFactory;
|
||||
private readonly bool _retainDriverConnection;
|
||||
public bool HasDriverSession { get; private set; }
|
||||
private bool _isBusy, _canSave = true;
|
||||
private CaptureBackendPreset _selectedBackend = null!;
|
||||
public bool IsBusy
|
||||
@ -61,10 +63,11 @@ public sealed class CameraSettingsViewModel : BindableBase
|
||||
public string Error { get => _error; private set => SetProperty(ref _error, value); }
|
||||
public bool CanSave => _canSave && !IsBusy;
|
||||
|
||||
public CameraSettingsViewModel(CameraInfo camera, CameraSettingsStore store, Func<ICameraService>? driverCameraFactory = null)
|
||||
public CameraSettingsViewModel(CameraInfo camera, CameraSettingsStore store, Func<ICameraService>? driverCameraFactory = null, bool retainDriverConnection = false)
|
||||
{
|
||||
_camera = camera; _store = store;
|
||||
_driverCameraFactory = driverCameraFactory ?? (() => new UvcCameraService());
|
||||
_retainDriverConnection = retainDriverConnection;
|
||||
DriverPropertiesCommand = new DelegateCommand(async () => await OpenDriverPropertiesAsync(), () => IsUsb && !IsBusy);
|
||||
SelectedResolution = Resolutions[0]; SelectedFrameRate = FrameRates[0];
|
||||
SelectedBackend = Backends[0];
|
||||
@ -92,16 +95,32 @@ public sealed class CameraSettingsViewModel : BindableBase
|
||||
try
|
||||
{
|
||||
service = _driverCameraFactory();
|
||||
// 属性页使用独立的短时连接;不要求先保存配置或启动 SOP。
|
||||
if (!await service.ConnectAsync(_camera, new UvcCaptureOptions { Backend = UvcCaptureBackend.DirectShow })) return;
|
||||
if (!service.CanShowDriverProperties || !await service.StartAsync()) return;
|
||||
var options = new UvcCaptureOptions
|
||||
{
|
||||
Backend = UvcCaptureBackend.DirectShow,
|
||||
Width = SelectedResolution.Width, Height = SelectedResolution.Height,
|
||||
Fps = SelectedFrameRate.Fps, Format = SelectedFormat == Formats[0] ? null : SelectedFormat
|
||||
};
|
||||
// 先应用最终视频模式,再打开属性页。正式采集复用这一连接,避免再次协商导致驱动重置。
|
||||
if (!await service.ConnectAsync(_camera, options)) return;
|
||||
if (!service.CanShowDriverProperties) return;
|
||||
await service.ConfigureUvcAsync(options);
|
||||
if (!await service.StartAsync()) return;
|
||||
SelectedBackend = Backends.Single(p => p.Backend == UvcCaptureBackend.DirectShow);
|
||||
await service.ShowDriverPropertiesAsync();
|
||||
HasDriverSession = await service.ShowDriverPropertiesAsync();
|
||||
}
|
||||
catch { /* 驱动不支持时静默跳过。 */ }
|
||||
finally
|
||||
{
|
||||
try { if (service is not null) await Task.Run(service.Dispose); }
|
||||
try
|
||||
{
|
||||
if (service is not null)
|
||||
{
|
||||
if (_retainDriverConnection && HasDriverSession) await Task.Run(service.Stop);
|
||||
else if (_retainDriverConnection) await Task.Run(service.Disconnect);
|
||||
else await Task.Run(service.Dispose);
|
||||
}
|
||||
}
|
||||
catch { /* 关闭失败不向界面抛异常。 */ }
|
||||
IsBusy = false;
|
||||
}
|
||||
|
||||
@ -26,7 +26,7 @@
|
||||
<ComboBox x:Name="CaptureBackendPicker" Grid.Column="1" ItemsSource="{Binding Backends}" SelectedItem="{Binding SelectedBackend, Mode=TwoWay}" HorizontalAlignment="Stretch" />
|
||||
</Grid>
|
||||
<Button x:Name="DriverPropertiesButton" Content="驱动属性" Command="{Binding DriverPropertiesCommand}" HorizontalAlignment="Left" />
|
||||
<TextBlock Text="无需先启动采集,点击即可打开相机驱动的原生设置。打开后采集方式切换为 DirectShow,点击“保存”保留选择。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
|
||||
<TextBlock Text="无需先启动采集。调整驱动选项后点击“保存”,正式采集会复用当前连接;如需改变分辨率或帧率,请先修改再打开驱动属性。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
|
||||
<TextBlock Text="列表为常用配置,不代表当前相机均支持。选择“驱动默认”可保留默认模式;实际协商结果见运行日志。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
|
||||
</StackPanel>
|
||||
<StackPanel IsVisible="{Binding IsIndustrial}" Spacing="8">
|
||||
|
||||
@ -133,7 +133,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
LoadRecipes();
|
||||
|
||||
// 命令接线(DelegateCommand 的可用条件都挂在这里)
|
||||
ConfigureCameraCommand = new DelegateCommand(async () => await ConfigureCameraAsync(), () => CanSelectCamera && SelectedCamera is not null && !IsConnected);
|
||||
ConfigureCameraCommand = new DelegateCommand(async () => await ConfigureCameraAsync(), () => CanSelectCamera && SelectedCamera is not null);
|
||||
RefreshCamerasCommand = new DelegateCommand(async () => await RefreshCamerasAsync(), () => CanSelectCamera);
|
||||
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
|
||||
TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
|
||||
@ -598,7 +598,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
_dispatcher.BeginInvoke(() => RefreshRecipes(fileName))));
|
||||
parameters.Add("cameraService", _camera);
|
||||
parameters.Add("selectedCameraProvider", new Func<CameraInfo?>(() => SelectedCamera));
|
||||
parameters.Add("canUseCamera", new Func<bool>(() => CanSelectCamera && !IsConnected));
|
||||
parameters.Add("canUseCamera", new Func<bool>(() => CanSelectCamera && (!IsConnected || !_camera.IsGrabbing)));
|
||||
if (SelectedCamera is not null) parameters.Add("cameraInfo", SelectedCamera);
|
||||
if (Frame is BitmapSource image)
|
||||
{
|
||||
@ -612,15 +612,17 @@ public class SopPageViewModel : ViewModelBase
|
||||
|
||||
private async Task ConfigureCameraAsync()
|
||||
{
|
||||
if (!CanSelectCamera || SelectedCamera is null || IsConnected) return;
|
||||
if (!CanSelectCamera || SelectedCamera is null) return;
|
||||
var camera = SelectedCamera;
|
||||
SetCameraBusy(true);
|
||||
try
|
||||
{
|
||||
var model = new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(camera, SopHelper.Models.CameraSettingsStore.Current);
|
||||
var model = new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(camera, SopHelper.Models.CameraSettingsStore.Current, () => _camera, retainDriverConnection: true);
|
||||
var dialog = new SopHelper.VVMs.CameraSettings.CameraSettingsWindow(model);
|
||||
if (await dialog.ShowDialog<bool>(DesktopPlatform.Owner))
|
||||
StatusText = "相机配置已保存,下次开启采集生效";
|
||||
else if (model.HasDriverSession)
|
||||
await Task.Run(_camera.Disconnect);
|
||||
}
|
||||
catch (Exception ex) { Log("error", "打开相机配置失败:" + ex.Message); }
|
||||
finally { SetCameraBusy(false); }
|
||||
|
||||
@ -3,14 +3,20 @@ namespace SopHelper.Engine.Camera;
|
||||
/// <summary>统一枚举、按设备类型切换采集后端,推理管线始终订阅同一个服务。</summary>
|
||||
public sealed class CameraService : ICameraService
|
||||
{
|
||||
private readonly ICameraService _uvc = new UvcCameraService();
|
||||
private readonly ICameraService _hik = new HikvisionCameraService();
|
||||
private readonly ICameraService _uvc;
|
||||
private readonly ICameraService _hik;
|
||||
private ICameraService? _active;
|
||||
private readonly SemaphoreSlim _operations = new(1, 1);
|
||||
private bool _disposed;
|
||||
|
||||
public CameraService()
|
||||
private CameraInfo? _connectedCamera;
|
||||
private UvcCaptureOptions? _connectionOptions, _configuredOptions;
|
||||
private string _modeDescription = "";
|
||||
|
||||
public CameraService(ICameraService? uvc = null, ICameraService? hik = null)
|
||||
{
|
||||
_uvc = uvc ?? new UvcCameraService();
|
||||
_hik = hik ?? new HikvisionCameraService();
|
||||
foreach (var service in new[] { _uvc, _hik })
|
||||
{
|
||||
service.FrameArrived += frame => FrameArrived?.Invoke(frame);
|
||||
@ -47,9 +53,20 @@ public sealed class CameraService : ICameraService
|
||||
try
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
options.Validate();
|
||||
if (camera.Kind == CameraKind.Uvc && _active?.IsConnected == true && _connectedCamera is { } current
|
||||
&& current.Kind == camera.Kind && current.Index == camera.Index && _connectionOptions == options)
|
||||
return true;
|
||||
_connectedCamera = null; _connectionOptions = null; _configuredOptions = null;
|
||||
if (_active is not null) await Task.Run(_active.Disconnect).ConfigureAwait(false);
|
||||
_active = camera.Kind == CameraKind.Hikvision ? _hik : _uvc;
|
||||
return await _active.ConnectAsync(camera, options).ConfigureAwait(false);
|
||||
var connected = await _active.ConnectAsync(camera, options).ConfigureAwait(false);
|
||||
if (connected)
|
||||
{
|
||||
_connectedCamera = new CameraInfo { Kind = camera.Kind, Index = camera.Index, SerialNumber = camera.SerialNumber };
|
||||
_connectionOptions = options with { };
|
||||
}
|
||||
return connected;
|
||||
}
|
||||
finally { _operations.Release(); }
|
||||
}
|
||||
@ -73,7 +90,13 @@ public sealed class CameraService : ICameraService
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_active is null || !_active.IsConnected) throw new InvalidOperationException("请先连接相机");
|
||||
return await _active.ConfigureUvcAsync(options).ConfigureAwait(false);
|
||||
options.Validate();
|
||||
// 设置属性页后重复 Set(FourCC/Width/Height/Fps) 可能重建采集图,重置驱动的图像控制。
|
||||
if (_configuredOptions == options) return _modeDescription;
|
||||
_configuredOptions = null;
|
||||
_modeDescription = await _active.ConfigureUvcAsync(options).ConfigureAwait(false);
|
||||
_configuredOptions = options with { };
|
||||
return _modeDescription;
|
||||
}
|
||||
finally { _operations.Release(); }
|
||||
}
|
||||
@ -107,7 +130,11 @@ public sealed class CameraService : ICameraService
|
||||
public void Disconnect()
|
||||
{
|
||||
_operations.Wait();
|
||||
try { if (!_disposed) _active?.Disconnect(); }
|
||||
try
|
||||
{
|
||||
if (!_disposed) _active?.Disconnect();
|
||||
_connectedCamera = null; _connectionOptions = null; _configuredOptions = null;
|
||||
}
|
||||
finally { _operations.Release(); }
|
||||
}
|
||||
|
||||
|
||||
@ -635,6 +635,30 @@ internal static class Smoke
|
||||
unsupportedModel.DriverPropertiesCommand.Execute();
|
||||
for(var i=0;i<50&&unsupportedModel.IsBusy;i++)await Task.Delay(20);
|
||||
Check(!unsupportedModel.IsBusy&&unsupported.DisposeCount==1&&unsupported.DriverPropertiesOpened==0,"Unavailable driver properties silently clean up the temporary connection");
|
||||
var nativeCamera=new FakeCamera {SupportsDriverProperties=true};
|
||||
using var sharedSession=new CameraService(nativeCamera,new FakeCamera());
|
||||
var sessionCamera=new CameraInfo {Index=7,Name="保留驱动设置测试"};
|
||||
var retainedModel=new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(sessionCamera,CameraSettingsStore.Current,()=>sharedSession,retainDriverConnection:true);
|
||||
retainedModel.SelectedResolution=retainedModel.Resolutions.Single(r=>r.Width==1280&&r.Height==720);
|
||||
retainedModel.SelectedFrameRate=retainedModel.FrameRates.Single(r=>r.Fps==30);
|
||||
retainedModel.DriverPropertiesCommand.Execute();
|
||||
for(var i=0;i<100&&retainedModel.IsBusy;i++)await Task.Delay(20);
|
||||
Check(retainedModel.HasDriverSession&&nativeCamera.IsConnected&&!nativeCamera.IsGrabbing&&nativeCamera.DisposeCount==0,
|
||||
"Closing properties retains the shared camera graph without leaving preview grabbing");
|
||||
Check(nativeCamera.ConfigureCount==1&&nativeCamera.NativeDriverAdjusted,"Video mode is applied before editing driver properties");
|
||||
Check(retainedModel.Save(),"Prepared camera mode is saved for acquisition");
|
||||
var sessionStore=CameraSettingsStore.Current;
|
||||
await sessionStore.ConnectAsync(sharedSession,sessionCamera);await sessionStore.ApplyAsync(sharedSession,sessionCamera);await sharedSession.StartAsync();
|
||||
Check(nativeCamera.ConnectCount==1&&nativeCamera.ConfigureCount==1&&nativeCamera.NativeDriverAdjusted&&nativeCamera.IsGrabbing,
|
||||
"Starting acquisition reuses the graph and does not reset the driver's native adjustment");
|
||||
sharedSession.Stop();await sessionStore.ConnectAsync(sharedSession,sessionCamera);await sessionStore.ApplyAsync(sharedSession,sessionCamera);
|
||||
Check(nativeCamera.ConnectCount==1&&nativeCamera.ConfigureCount==1,"Stopping grabbing without disconnecting preserves the prepared mode");
|
||||
var changed=sessionStore.Load(sessionCamera);changed.UsbCapture.Fps=15;sessionStore.Save(sessionCamera,changed);
|
||||
await sessionStore.ConnectAsync(sharedSession,sessionCamera);await sessionStore.ApplyAsync(sharedSession,sessionCamera);
|
||||
Check(nativeCamera.ConnectCount==2&&nativeCamera.ConfigureCount==2&&!nativeCamera.NativeDriverAdjusted,
|
||||
"Explicit video mode changes reconnect and are never hidden by the reuse cache");
|
||||
sharedSession.Disconnect();await sessionStore.ConnectAsync(sharedSession,sessionCamera);await sessionStore.ApplyAsync(sharedSession,sessionCamera);
|
||||
Check(nativeCamera.ConnectCount==3&&nativeCamera.ConfigureCount==3,"Disconnect invalidates the prepared connection and mode");
|
||||
}
|
||||
|
||||
private static async Task CheckCompletionImageSaving(App app,SopPageViewModel sop)
|
||||
@ -948,16 +972,19 @@ internal sealed class FakeCamera : ICameraService
|
||||
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 int ConnectCount {get;private set;}
|
||||
public int ConfigureCount {get;private set;}
|
||||
public bool NativeDriverAdjusted {get;private set;}
|
||||
public Task<bool> ConnectAsync(CameraInfo camera){ConnectCount++;NativeDriverAdjusted=false;IsConnected=true;ConnectionChanged?.Invoke(true);return Task.FromResult(true);}
|
||||
public UvcCaptureOptions? LastConnectionOptions {get;private set;}
|
||||
public Task<bool> ConnectAsync(CameraInfo camera,UvcCaptureOptions options){LastConnectionOptions=options with {};return ConnectAsync(camera);}
|
||||
public bool SupportsDriverProperties {get;set;}
|
||||
public bool CanShowDriverProperties=>SupportsDriverProperties;
|
||||
public int DriverPropertiesOpened {get;private set;}
|
||||
public TaskCompletionSource<bool>? DriverPropertiesCompletion {get;set;}
|
||||
public Task<bool> ShowDriverPropertiesAsync(){DriverPropertiesOpened++;return DriverPropertiesCompletion?.Task??Task.FromResult(SupportsDriverProperties);}
|
||||
public Task<bool> ShowDriverPropertiesAsync(){DriverPropertiesOpened++;NativeDriverAdjusted=true;return DriverPropertiesCompletion?.Task??Task.FromResult(SupportsDriverProperties);}
|
||||
public UvcCaptureOptions? LastUsbOptions {get;private set;}
|
||||
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options){LastUsbOptions=options with {};return Task.FromResult("test USB mode");}
|
||||
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options){ConfigureCount++;NativeDriverAdjusted=false;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 int DisposeCount {get;private set;} public void Dispose(){DisposeCount++;Disconnect();}
|
||||
private long _id;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user