停止采集时保留连接并在切换相机或退出时释放

This commit is contained in:
tfarcraw 2026-11-18 21:58:45 +08:00
parent f0f5e650bc
commit 4de0450c08
5 changed files with 128 additions and 17 deletions

View File

@ -26,6 +26,8 @@ pwsh -File tools/Start-HandAiD3.ps1
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。
6. 过程图区显示实际送检的完成帧;日志显示帧号、裁剪范围、模型完成概率和耗时。完成图按步骤设置保存到配方目录。
主页面只显示运行状态,推理后端诊断记录在运行日志中。SOP 停止采集时保留相机连接;再次开始复用同一设备,USB 参数未改变时不重复设置视频模式。切换相机、设备消失或退出程序时释放连接;采集失败时释放连接以便重试。停止后仍可修改相机配置和编辑配方。
SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配方的 `sop_stand` 目录。配方选择和相机选择会记忆;恢复选择不会自动开始采集。
“Agent助手”接收本地标准视频路径,通过工具自主查看不同时间点、继续检查细节,再生成步骤草稿。模型需支持 Chat Completions 工具调用和图片输入,不需要上传完整视频。每次工具读取上限默认 3 张,可修改并记住。草稿包含时间段、参考画面、步骤说明和手部规则,修改后追加到配方,最后手动保存。接口地址、模型名、密钥及生成参数自动保存,下次启动恢复;模型列表可自动获取。运行时仍由 D3-lite 确认步骤完成。详细限制与配置见 [HAND_AI.md](HAND_AI.md)。

View File

@ -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);
@ -184,9 +184,15 @@ public class SopPageViewModel : ViewModelBase
get { return _selectedCamera; }
set
{
var previous = _selectedCamera;
if (!SetProperty(ref _selectedCamera, value)) return;
// 枚举时清空、恢复列表是程序行为;只有操作员选择才更新偏好。
if (value is not null && !_isCameraBusy) RememberCamera(value);
// 枚举时清空、恢复列表不释放已连接的设备;只有实际选择变化才释放旧设备。
if (!_isCameraBusy)
{
if (value is not null) RememberCamera(value);
if (_camera.IsConnected && previous is not null && !previous.IsSameDevice(value))
_ = ReleaseCameraForSelectionAsync();
}
RaiseCommands(); // 实测:不刷新会导致"开始/停止"一直灰着,选了相机也点不动
}
}
@ -339,6 +345,19 @@ public class SopPageViewModel : ViewModelBase
public DelegateCommand NewRecipeCommand { get; private set; } = null!;
public DelegateCommand OpenRecipeFolderCommand { get; private set; } = null!;
private async Task ReleaseCameraForSelectionAsync()
{
SetCameraBusy(true);
try
{
await Task.Run(() => { _pipeline.Stop(); _camera.Disconnect(); });
IsConnected = false;
StatusText = "相机选择已更改";
}
catch (Exception ex) { Log("warn", "释放旧相机失败:" + ex.Message); }
finally { if (!_destroyed) SetCameraBusy(false); }
}
private bool CanStart() => !_isCameraBusy && !_deletingRecipe &&
(IsRunning || (SelectedCamera is not null && SelectedRecipe is not null && Recipes.Contains(SelectedRecipe)));
@ -351,7 +370,7 @@ public class SopPageViewModel : ViewModelBase
/// <summary>运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用</summary>
private bool CanEditRecipe() => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe);
private bool CanDeleteRecipe() => CanSelectCamera && !IsConnected && SelectedRecipe is not null && Recipes.Contains(SelectedRecipe);
private bool CanDeleteRecipe() => CanSelectCamera && !_camera.IsGrabbing && SelectedRecipe is not null && Recipes.Contains(SelectedRecipe);
/// <summary>
/// 刷新所有命令的可用状态。Prism 的 DelegateCommand 只在被显式 raise 时才重估 CanExecute,
@ -521,7 +540,7 @@ public class SopPageViewModel : ViewModelBase
{
var name = Path.GetFileNameWithoutExtension(fileName);
if (!await ConfirmDeleteRecipeAsync(name)) { StatusText = "已取消删除配方"; return; }
if (_destroyed || IsRunning || _isCameraBusy || IsConnected) return;
if (_destroyed || IsRunning || _isCameraBusy || _camera.IsGrabbing) return;
wasActive = ActiveRecipe == fileName;
if (wasActive) ClearActiveRecipe();
var archive = DesktopPlatform.Recipes.Delete(name);
@ -598,7 +617,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 && !_camera.IsGrabbing));
if (SelectedCamera is not null) parameters.Add("cameraInfo", SelectedCamera);
if (Frame is BitmapSource image)
{
@ -612,7 +631,7 @@ 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
@ -671,13 +690,17 @@ public class SopPageViewModel : ViewModelBase
if (Cameras.Count == 0)
{
Log("warn", "没有枚举到相机(支持 UVC、海康 GigE/USB 工业相机)");
if (_camera.IsConnected) await Task.Run(_camera.Disconnect);
return;
}
SelectedCamera = previous is null ? Cameras[0] : Cameras.FirstOrDefault(c => c.Kind == previous.Kind &&
(c.Kind == CameraKind.Hikvision ? c.SerialNumber == previous.SerialNumber : c.Index == previous.Index));
if (previous is not null && SelectedCamera is null)
{
if (_camera.IsConnected) await Task.Run(_camera.Disconnect);
Log("warn", $"上次选择的相机「{previous.Name}」未找到,请检查连接后刷新,或手动选择其他相机");
}
Log("info", $"枚举到 {Cameras.Count} 个相机");
}
catch (Exception ex)
@ -709,11 +732,10 @@ public class SopPageViewModel : ViewModelBase
await Task.Run(() =>
{
_pipeline.Stop();
// Recording opens its own capture session; stopping SOP must release the device.
_camera.Disconnect();
// 只停止取帧与处理,保留设备连接供再次开始复用。
});
IsRunning = false;
StatusText = "已停止";
StatusText = "已停止采集,连接保留";
return;
}

View File

@ -8,6 +8,9 @@ public sealed class CameraService : ICameraService
private ICameraService? _active;
private readonly SemaphoreSlim _operations = new(1, 1);
private bool _disposed;
private CameraInfo? _connectedCamera;
private UvcCaptureOptions? _configuredUsbOptions;
private string _modeDescription = "";
public CameraService(ICameraService? uvc = null, ICameraService? hik = null)
{
@ -48,9 +51,17 @@ public sealed class CameraService : ICameraService
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_active?.IsConnected == true && camera.IsSameDevice(_connectedCamera)
&& (camera.Kind != CameraKind.Uvc || camera.UseCompatibilityBackend == _connectedCamera!.UseCompatibilityBackend))
return true;
_connectedCamera = null; _configuredUsbOptions = 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).ConfigureAwait(false);
var connected = await _active.ConnectAsync(camera).ConfigureAwait(false);
if (connected)
_connectedCamera = new CameraInfo {Kind=camera.Kind,Index=camera.Index,SerialNumber=camera.SerialNumber,
UseCompatibilityBackend=camera.UseCompatibilityBackend};
return connected;
}
finally { _operations.Release(); }
}
@ -74,7 +85,12 @@ 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();
if (_configuredUsbOptions == options) return _modeDescription;
_configuredUsbOptions = null;
_modeDescription = await _active.ConfigureUvcAsync(options).ConfigureAwait(false);
_configuredUsbOptions = options with { };
return _modeDescription;
}
finally { _operations.Release(); }
}
@ -103,6 +119,8 @@ public sealed class CameraService : ICameraService
try
{
if (!_disposed) _active?.Disconnect();
_active = null;
_connectedCamera = null; _configuredUsbOptions = null;
}
finally { _operations.Release(); }
}

View File

@ -20,6 +20,10 @@ public class CameraInfo
/// <summary>Windows 内部兼容采集标记;由枚举结果决定,不作为用户设置。</summary>
public bool UseCompatibilityBackend { get; set; }
public bool IsSameDevice(CameraInfo? other) => other is not null && Kind == other.Kind &&
(Kind == CameraKind.Hikvision && (!string.IsNullOrWhiteSpace(SerialNumber) || !string.IsNullOrWhiteSpace(other.SerialNumber))
? !string.IsNullOrWhiteSpace(SerialNumber) && SerialNumber == other.SerialNumber : Index == other.Index);
/// <summary>名称</summary>
public string Name { get; set; } = "";
}
@ -88,7 +92,7 @@ public interface ICameraService : IDisposable
/// <summary>开始采集</summary>
Task<bool> StartAsync();
/// <summary>停止采集</summary>
/// <summary>停止采集,保留设备连接。</summary>
void Stop();
/// <summary>断开</summary>

View File

@ -65,6 +65,8 @@ internal static class Smoke
var lifetime=(IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!;
lifetime.Startup+=(_,_)=>Dispatcher.UIThread.Post(async()=>await Run(lifetime));
}).StartWithClassicDesktopLifetime([],ShutdownMode.OnExplicitShutdown);
if(args.Contains("--camera-lifecycle-only")&&_exit==0)
Check(!Camera.IsConnected&&Camera.DisposeCount>0,"Application exit releases the retained camera connection");
}
finally
{
@ -106,6 +108,7 @@ internal static class Smoke
Check(model.Logs.Any(l=>l.Message.Contains("推理设备:")&&l.Message.Contains("步骤确认=")),"Inference backend diagnostics remain available in the runtime log");
_exit=0;return;
}
if(Environment.GetCommandLineArgs().Contains("--camera-lifecycle-only")) { await CheckCameraLifecycle(app,window); _exit=0; return; }
if(Environment.GetCommandLineArgs().Contains("--usb-capture-only")) { await CheckUsbCapture(app); _exit=0; return; }
CheckCameraPreferences(app);
CheckRecipePreferences(app);
@ -158,7 +161,7 @@ internal static class Smoke
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");
Check(!sop.IsRunning&&Camera.IsConnected&&!Camera.IsGrabbing,"Stop command retains the idle camera connection");
await CheckProcessImages(app,sop,window);
await CheckRuntimeStatistics(app,sop,window);
await CheckCompletionImageSaving(app,sop);
@ -579,6 +582,65 @@ internal static class Smoke
finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
}
private static async Task CheckCameraLifecycle(App app,Window window)
{
var uvc=new FakeCamera();var hik=new FakeCamera();
var service=new CameraService(uvc,hik);
var camera=new CameraInfo {Index=0,UseCompatibilityBackend=true};
var mode=new UvcCaptureOptions {Width=1280,Height=720,Fps=30};
await service.ConnectAsync(camera);await service.ConfigureUvcAsync(mode);await service.StartAsync();service.Stop();
Check(service.IsConnected&&!service.IsGrabbing&&uvc.DisconnectCount==0,"Stop preserves the physical camera connection");
await service.ConnectAsync(new CameraInfo {Index=0,Name="刷新后的同一相机",UseCompatibilityBackend=true});
await service.ConfigureUvcAsync(mode with {});await service.StartAsync();
Check(uvc.ConnectCount==1&&uvc.ConfigureCount==1&&service.IsGrabbing,"Resume reuses the device and skips unchanged video parameters");
service.Stop();await service.ConfigureUvcAsync(mode with {Fps=15});
Check(uvc.ConnectCount==1&&uvc.ConfigureCount==2,"Changed camera parameters are applied to the retained connection");
await service.ConnectAsync(new CameraInfo {Index=1,UseCompatibilityBackend=true});
await service.ConfigureUvcAsync(mode);
Check(uvc.DisconnectCount==1&&uvc.ConnectCount==2&&uvc.ConfigureCount==3,"Switching USB cameras releases the previous device and invalidates mode cache");
await service.ConnectAsync(new CameraInfo {Kind=CameraKind.Hikvision,SerialNumber="test-serial",Index=2});
await service.ConnectAsync(new CameraInfo {Kind=CameraKind.Hikvision,SerialNumber="test-serial",Index=9});
Check(uvc.DisconnectCount==2&&hik.ConnectCount==1,"Industrial cameras also reuse their connection by serial number");
service.Disconnect();var released=hik.DisconnectCount;
await service.ConnectAsync(new CameraInfo {Kind=CameraKind.Hikvision,SerialNumber="test-serial",Index=9});
Check(hik.DisconnectCount==released&&hik.ConnectCount==2,"Reconnecting an explicitly released device does not release it a second time");
service.Dispose();service.Dispose();
Check(uvc.DisposeCount==1&&hik.DisposeCount==1&&!hik.IsConnected,"Exit disposes each camera service once");
var rejected=false;try{await service.ConnectAsync(camera);}catch(ObjectDisposedException){rejected=true;}
Check(rejected,"Disposed services cannot reopen a camera");
var sop=app.Container.Resolve<SopPageViewModel>();
var workspace=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
const string name="相机生命周期";var path=workspace.ConfigPath(name);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
config.Sop.Steps.Add(new(){Id=1,Name="等待",Detection=new(){Method="time_elapsed",DurationMs=600000,StableFrames=1}});
SopHelper.Engine.Sop.SopConfigLoader.Save(config,path);
sop.Recipes.Add(name+".yaml");sop.SelectedRecipe=name+".yaml";
sop.StartStopCommand.Execute();
for(var i=0;i<250&&!sop.IsRunning;i++)await Task.Delay(20);
Check(sop.IsRunning&&Camera.IsGrabbing,"Main page starts acquisition");
var disconnects=Camera.DisconnectCount;
sop.StartStopCommand.Execute();
for(var i=0;i<250&&(sop.IsRunning||!sop.CanSelectCamera);i++)await Task.Delay(20);
Check(!sop.IsRunning&&sop.IsConnected&&Camera.IsConnected&&!Camera.IsGrabbing&&Camera.DisconnectCount==disconnects,
"Main-page stop leaves an idle connected camera");
Check(sop.ConfigureCameraCommand.CanExecute()&&sop.EditRecipeCommand.CanExecute()&&sop.DeleteRecipeCommand.CanExecute(),
"Idle retained connections do not block configuration or recipe editing");
sop.RefreshCamerasCommand.Execute();
for(var i=0;i<250&&!sop.CanSelectCamera;i++)await Task.Delay(20);
Check(Camera.DisconnectCount==disconnects,"Refreshing the list preserves the selected device connection");
var other=new CameraInfo {Index=1,Name="第二台测试相机"};Camera.Devices.Add(other);sop.SelectedCamera=other;
for(var i=0;i<250&&(!sop.CanSelectCamera||Camera.IsConnected);i++)await Task.Delay(20);
Check(!Camera.IsConnected&&Camera.DisconnectCount==disconnects+1,"Changing selection releases the old camera immediately before another start");
sop.StartStopCommand.Execute();for(var i=0;i<250&&!sop.IsRunning;i++)await Task.Delay(20);
Check(sop.IsRunning,"The newly selected camera starts successfully");
sop.StartStopCommand.Execute();for(var i=0;i<250&&(sop.IsRunning||!sop.CanSelectCamera);i++)await Task.Delay(20);
Check(Camera.IsConnected&&!Camera.IsGrabbing,"The new device is retained after stopping");
Check(!window.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Name=="InferenceBackend")&&
sop.Logs.Any(l=>l.Message.Contains("推理设备:")&&l.Message.Contains("步骤确认=")),"Diagnostic details remain in logs only");
}
private static async Task CheckUsbCapture(App app)
{
foreach(var invalid in new UvcCaptureOptions[] {new(){Width=1920},new(){Width=0,Height=1080},new(){Fps=double.NaN},new(){Fps=-1},new(){Format="bad"},new(){AutoExposure=false,ExposureTimeMs=0},new(){AutoExposure=true,ExposureTimeMs=10}})
@ -961,11 +1023,14 @@ 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 int DisconnectCount {get;private set;}
public Task<bool> ConnectAsync(CameraInfo camera){ConnectCount++;IsConnected=true;ConnectionChanged?.Invoke(true);return Task.FromResult(true);}
public UvcCaptureOptions? LastUsbOptions {get;private set;}
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options){LastUsbOptions=options with {};return Task.FromResult("test USB mode");}
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options){ConfigureCount++;LastUsbOptions=options with {};return Task.FromResult("test USB mode");}
public Task<bool> StartAsync(){IsGrabbing=true;return Task.FromResult(true);}
public void Stop(){IsGrabbing=false;}public void Disconnect(){Stop();IsConnected=false;ConnectionChanged?.Invoke(false);}public int DisposeCount {get;private set;} public void Dispose(){DisposeCount++;Disconnect();}
public void Stop(){IsGrabbing=false;}public void Disconnect(){DisconnectCount++;Stop();IsConnected=false;ConnectionChanged?.Invoke(false);}public int DisposeCount {get;private set;} public void Dispose(){DisposeCount++;Disconnect();}
private long _id;
public void Emit(int? objectX=null)
{