aisop/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs

1565 lines
66 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// SOP 操作页协调层:连接配方、相机、推理管线与状态机,维护预览、步骤卡、统计和日志。
using System.Collections.ObjectModel;
using System.IO;
using System.Diagnostics;
using System.Text.Json;
using Avalonia.Media;
using ImageSource = Avalonia.Media.IImage;
using SopHelper.Presentation.Imaging;
using SopHelper.Presentation;
using SopHelper.Presentation.Threading;
using OpenCvSharp;
using Prism.Commands;
using Prism.Dialogs;
using SopHelper.Core.Prism;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Common;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Recipes;
using SopHelper.SopVideo;
namespace SopHelper.VVMs.SopPage;
/// <summary>
/// SOP 主页视图模型:相机 → 推理管线 → SOP 引擎,界面只订阅事件。
/// </summary>
public class SopPageViewModel : ViewModelBase
{
private static readonly System.Net.Http.HttpClient VisionHttp = new() { Timeout = System.Threading.Timeout.InfiniteTimeSpan };
private const int MaxLogLines = 300;
/// <summary>配方目录(相对程序目录)</summary>
private static string RecipeDirectory => DesktopPlatform.Recipes.RecipesDirectory;
private static string RecipePath(string fileName) => DesktopPlatform.Recipes.ConfigPath(Path.GetFileNameWithoutExtension(fileName));
private static string LastRecipePath => Path.Combine(DesktopPlatform.WorkspaceRoot, "workspace", "last-recipe.json");
// 独立工作区(包括自动化测试)不能覆盖正式程序的用户偏好。
private static string LastCameraPath =>
!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT"))
? Path.Combine(DesktopPlatform.WorkspaceRoot, "workspace", "last-camera.json")
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SopHelper", "last-camera.json");
/// <summary>配方编辑器弹窗的注册名(见 App.RegisterTypes)</summary>
private const string EditorDialogName = "RecipeEditorDialog";
private readonly ICameraService _camera;
private readonly DetectionPipeline _pipeline;
private readonly SopEngine _engine;
private readonly IDialogService _dialogs;
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _statisticsTimer;
private long _completedCount;
private string _flowElapsedText = "00:00:00", _stepElapsedText = "00:00:00";
private string _standardDurationText = "00:00:00", _averageDurationText = "00:00:00";
public long CompletedCount { get => _completedCount; private set => SetProperty(ref _completedCount, value); }
public string FlowElapsedText { get => _flowElapsedText; private set => SetProperty(ref _flowElapsedText, value); }
public string StepElapsedText { get => _stepElapsedText; private set => SetProperty(ref _stepElapsedText, value); }
public string StandardDurationText { get => _standardDurationText; private set => SetProperty(ref _standardDurationText, value); }
public string AverageDurationText { get => _averageDurationText; private set => SetProperty(ref _averageDurationText, value); }
public static string FormatDuration(TimeSpan duration) => $"{(long)duration.TotalHours:00}:{duration.Minutes:00}:{duration.Seconds:00}";
private int _renderQueued;
/// <summary>采集线程写、UI 线程取最新帧;最多排队一个刷新请求</summary>
private readonly object _frameLock = new();
private Mat? _pending;
private bool _destroyed;
/// <summary>最近一次处理过的帧(快照按钮存盘用,由推理线程写入)</summary>
private FrameResult? _lastFrame;
private Mat? _judgementFrame;
private Task _completionImageSaves = Task.CompletedTask;
private FrameResult? _handResult;
private WriteableBitmap? _bitmap;
private long _frameCount;
private long _lastTickCount;
private readonly Stopwatch _fpsClock = Stopwatch.StartNew();
private CameraInfo? _selectedCamera;
private CameraInfo? _lastUsedCamera;
private string? _selectedRecipe;
private bool _refreshingRecipes;
private bool _deletingRecipe;
/// <summary>导入/导出进行中标记:期间锁定配方与相机操作,避免解压时列表、选择或采集同时变化。</summary>
private bool _transferringRecipe;
public Func<string, Task<bool>>? ConfirmDeleteRecipeAsync { get; set; }
/// <summary>同名配方导入前向设置页请求确认(覆盖 / 另存新名 / 取消);未接上时按取消处理,不擅自覆盖现场配方。</summary>
public Func<ImportConflict, Task<ImportConflictChoice>>? ConfirmImportConflictAsync { get; set; }
/// <summary>同名配方导入的确认信息:包路径、包摘要和已算好的可用名称。</summary>
/// <param name="PackagePath">用户选择的配方包文件路径。</param>
/// <param name="Info">包摘要,含配方名、文件数、体积与提醒。</param>
/// <param name="SuggestedName">改名导入时将使用的可用配方名。</param>
public sealed record ImportConflict(string PackagePath, SopHelper.Engine.Recipes.RecipePackage.PackageInfo Info, string SuggestedName);
/// <summary>同名配方导入的用户选择。</summary>
public enum ImportConflictChoice { Cancel, Overwrite, SaveAsNew }
private string _activeRecipe = "未应用配方";
private ImageSource? _frame;
private string _statusText = "就绪";
private string _fpsText = "—";
private string _inferenceText = "—";
private bool _isRunning;
private bool _isConnected;
private bool _isCameraBusy;
private double _frameWidth;
private double _frameHeight;
private double _confidence = 0.6;
private readonly SopHelper.Models.RuntimeSettingsStore _runtimeStore = SopHelper.Models.RuntimeSettingsStore.Current;
private SopHelper.Models.RuntimeOptions _runtimeOptions = new();
/// <summary>
/// SOP 主页视图模型
/// </summary>
public SopPageViewModel(ICameraService camera, DetectionPipeline pipeline, SopEngine engine, IDialogService dialogs)
{
_camera = camera;
_pipeline = pipeline;
_engine = engine;
_engine.StepCountStore ??= SopHelper.Models.StepCountsStore.Current;
_engine.VisionDecisionClient ??= new ConfiguredVisionDecisionClient(VisionHttp);
_pipeline.ShouldDetectHands = () => _engine.RequiresHandDetection;
_dialogs = dialogs;
_dispatcher = Dispatcher.CurrentDispatcher;
_runtimeOptions = _runtimeStore.Read() ?? new();
_camera.ConnectionChanged += on => _dispatcher.BeginInvoke(() =>
{
IsConnected = on;
if (!on && IsRunning)
{
IsRunning = false;
StatusText = "相机已断开";
RaiseCommands();
}
});
_camera.Error += message => _dispatcher.BeginInvoke(() => Log("warn", message));
_pipeline.ResultFrameArrived += OnResultFrame;
_pipeline.InferenceWarning += message => _dispatcher.BeginInvoke(() => Log("warn", message));
// 帧 Mat 只在采集线程的事件存活期内有效(事件返回即被释放),必须当场克隆
_camera.FrameArrived += OnCameraFrame;
_engine.LogArrived += entry => _dispatcher.BeginInvoke(() => AppendLog(entry));
_engine.StepSnapshotChanged += OnStepSnapshot;
_engine.RoundStarted += OnRoundStarted;
_engine.RoundFinished += OnRoundFinished;
LoadRecipes();
Access.SessionChanged += AccessChanged;
// 命令接线(DelegateCommand 的可用条件都挂在这里)
ConfigureCameraCommand = ConfigurationCommand(async () => await ConfigureCameraAsync(), () => CanSelectCamera && SelectedCamera is not null);
RefreshCamerasCommand = ConfigurationCommand(async () => await RefreshCamerasAsync(), () => CanSelectCamera);
StartStopCommand = new DelegateCommand(async () => { if (Access.CheckPermission(Access.IsAuthenticated, "启动或停止运行") && CanStart()) await StartStopAsync(); }, () => !Access.IsAuthenticated || CanStart());
ResetCountsCommand = ConfigurationCommand(ResetCounts, () => StepCards.Count > 0);
PlayStandardSopCommand = ConfigurationCommand(async () => await ToggleStandardSopAsync(), () => !_isCameraBusy && !_deletingRecipe && !_transferringRecipe
&& (_standardSopCancellation is not null || StandardSopVideoPath is { } path && File.Exists(path)));
ApplyRecipeCommand = ConfigurationCommand(ApplyRecipe, () => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe));
SnapshotCommand = ConfigurationCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = ConfigurationCommand(EditRecipe, CanEditRecipe);
NewRecipeCommand = ConfigurationCommand(NewRecipe, () => CanSelectCamera);
DeleteRecipeCommand = ConfigurationCommand(async () => await DeleteRecipeAsync(), CanDeleteRecipe, false, "删除配方");
ImportRecipeCommand = ConfigurationCommand(async () => await ImportRecipeAsync(), CanImportRecipe, false, "导入配方");
ExportRecipeCommand = ConfigurationCommand(async () => await ExportRecipeAsync(), CanExportRecipe, false, "导出配方");
OpenRecipeFolderCommand = ConfigurationCommand(() =>
{
try { DesktopPlatform.Reveal(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(SelectedRecipe!))); }
catch (Exception error) { Log("warn", "打开配方目录失败:" + error.Message); }
}, () => !string.IsNullOrWhiteSpace(SelectedRecipe));
StatusText = "就绪,请确认运行设置后开始";
LoadLastCamera();
_ = RefreshCamerasAsync();
_statisticsTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
_statisticsTimer.Tick += (_, _) => RefreshStatistics();
_statisticsTimer.Start();
try { ApplyRecipe(); }
catch (Exception error)
{
StatusText = "自动应用配方失败,请检查配方后重试";
Log("warn", "自动应用配方失败:" + error.Message);
}
RefreshStatistics();
_accessReady = true;
}
/// <summary>可用相机</summary>
public ObservableCollection<CameraInfo> Cameras { get; } = [];
/// <summary>可用配方文件</summary>
public ObservableCollection<string> Recipes { get; } = [];
/// <summary>步骤卡</summary>
public ObservableCollection<StepCard> StepCards { get; } = [];
/// <summary>日志</summary>
public ObservableCollection<LogItem> Logs { get; } = [];
/// <summary>将 D3 启动消息调度到界面线程,按错误标志选择日志级别。</summary>
public void ReportD3Service(string message, bool error = false)
=> _dispatcher.BeginInvoke(() => Log(error ? "warn" : "info", message));
/// <summary>画面 ROI</summary>
public ObservableCollection<RoiItem> Rois { get; } = [];
/// <summary>选中相机</summary>
public CameraInfo? SelectedCamera
{
get { return _selectedCamera; }
set
{
if (_accessReady && !_isCameraBusy && !CanChangeSettings) return;
var previous = _selectedCamera;
if (!SetProperty(ref _selectedCamera, value)) return;
// 枚举时清空、恢复列表不释放已连接的设备;只有实际选择变化才释放旧设备。
if (!_isCameraBusy)
{
if (value is not null) RememberCamera(value);
if (_camera.IsConnected && previous is not null && !previous.IsSameDevice(value))
_ = ReleaseCameraForSelectionAsync();
}
RaiseCommands(); // 实测:不刷新会导致"开始/停止"一直灰着,选了相机也点不动
}
}
/// <summary>选中配方</summary>
public string? SelectedRecipe
{
get { return _selectedRecipe; }
set
{
if (_accessReady && !_refreshingRecipes && !CanChangeSettings) return;
if (!SetProperty(ref _selectedRecipe, value)) return;
if (!_refreshingRecipes) RememberRecipe(value);
RaiseCommands();
RefreshStatistics();
}
}
/// <summary>已成功应用的配方,与设置页尚未应用的选择分开。</summary>
public string ActiveRecipe
{
get => _activeRecipe;
private set => SetProperty(ref _activeRecipe, value);
}
/// <summary>画面</summary>
public ImageSource? Frame
{
get { return _frame; }
set { if (SetProperty(ref _frame, value)) RaisePropertyChanged(nameof(PreviewFrame)); }
}
/// <summary>最近一次推理结果,供图像上的手部与目标检测绘制层使用。</summary>
public FrameResult? HandResult
{
get => _handResult;
private set => SetProperty(ref _handResult, value);
}
/// <summary>状态</summary>
public string StatusText
{
get { return _statusText; }
set { SetProperty(ref _statusText, value); }
}
/// <summary>结果帧率</summary>
public string FpsText
{
get { return _fpsText; }
set { SetProperty(ref _fpsText, value); }
}
/// <summary>推理耗时</summary>
public string InferenceText
{
get { return _inferenceText; }
set { SetProperty(ref _inferenceText, value); }
}
/// <summary>实际推理设备,CPU 回退时直接显示在运行界面。</summary>
private static string VisionProviderName => Environment.GetEnvironmentVariable("SOPHELPER_VISION_PROVIDER")?.ToLowerInvariant() switch { "laya" => "Laya", "chat-completions" => "视觉模型", _ => "djev" };
public string InferenceBackendText => $"手部:{_pipeline.HandBackend};步骤确认:{VisionProviderName}";
/// <summary>是否运行中</summary>
public bool IsRunning
{
get { return _isRunning; }
set
{
if (!SetProperty(ref _isRunning, value)) return;
if (!value) { HandResult = null; _engine.Stop(); }
RaisePropertyChanged(nameof(CanSelectCamera)); RaisePropertyChanged(nameof(CanChangeSettings)); RaisePropertyChanged(nameof(CanChangeModels));
RaiseCommands();
RefreshStatistics();
}
}
/// <summary>共享身份与设置权限;后台恢复设备和配方仍可在登录前完成。</summary>
public SopHelper.Models.UserAccess Access => SopHelper.Models.UserAccess.Current;
public bool CanChangeSettings => Access.CanConfigure && CanSelectCamera;
public bool CanChangeModels => Access.IsAdministrator && CanSelectCamera;
// 无权限时保留点击入口用于显示提示;业务忙碌等非权限条件仍按原逻辑禁用。
// 执行委托再次校验角色,保证提示窗口不会替代实际的授权拦截。
// operation 只影响提示措辞(如“导入配方”),不改变判定;管理员操作仍按管理员权限判定。
private DelegateCommand ConfigurationCommand(Action action, Func<bool> available, bool administrator = false, string? operation = null)
{
bool Authorized() => administrator ? Access.IsAdministrator : Access.CanConfigure;
var deniedOperation = operation ?? (administrator ? "修改模型配置" : "执行此操作");
return new DelegateCommand(() =>
{
if (Access.CheckPermission(Authorized(), deniedOperation) && available()) action();
}, () => !Authorized() || available());
}
private void AccessChanged()
{
RaisePropertyChanged(nameof(CanChangeSettings));
RaisePropertyChanged(nameof(CanChangeModels));
RaiseCommands();
}
/// <summary>连接、枚举、采集、删除和配方包传输期间不切换设备,也不改动配方列表。</summary>
public bool CanSelectCamera => !IsRunning && !_isCameraBusy && !_deletingRecipe && !_transferringRecipe;
/// <summary>导入不需要选中配方(全新工作区也要能导入),只需要不在运行和传输中。</summary>
private bool CanImportRecipe() => CanSelectCamera;
/// <summary>导出需要一个已存在的选中配方;运行中允许导出,导出只读不改配方。</summary>
private bool CanExportRecipe() => CanSelectCamera && SelectedRecipe is { Length: > 0 } && File.Exists(RecipePath(SelectedRecipe));
/// <summary>配方包传输期间统一锁定相机、配方选择和配方命令,结束时无论成败都解锁。</summary>
private void SetRecipeTransfer(bool busy)
{
_transferringRecipe = busy;
RaisePropertyChanged(nameof(CanSelectCamera)); RaisePropertyChanged(nameof(CanChangeSettings)); RaisePropertyChanged(nameof(CanChangeModels));
RaiseCommands();
}
/// <summary>相机是否已连接</summary>
public bool IsConnected
{
get { return _isConnected; }
set
{
if (!SetProperty(ref _isConnected, value)) return;
RaisePropertyChanged(nameof(ConnectionText));
RaiseCommands();
}
}
/// <summary>右下角连接文字(实测静态文字不反映状态,改成绑定)</summary>
public string ConnectionText => IsConnected ? "相机已连接" : "相机未连接";
/// <summary>画面像素宽(ROI 覆盖层按它缩放)</summary>
public double FrameWidth
{
get { return _frameWidth; }
set { SetProperty(ref _frameWidth, value); }
}
/// <summary>画面像素高</summary>
public double FrameHeight
{
get { return _frameHeight; }
set { SetProperty(ref _frameHeight, value); }
}
/// <summary>旧版阈值字段(不参与当前推理)</summary>
public double Confidence
{
get { return _confidence; }
set { SetProperty(ref _confidence, value); }
}
/// <summary>抽帧间隔</summary>
public int FrameStride
{
get => _runtimeOptions.FrameStride;
set { if (!CanChangeSettings || value == FrameStride) return; _runtimeOptions.FrameStride = Math.Clamp(value, 1, 10); SaveRuntimeOptions(); }
}
public bool AutoResetOnComplete
{
get => _runtimeOptions.AutoResetOnComplete;
set { if (!CanChangeSettings || value == AutoResetOnComplete) return; _runtimeOptions.AutoResetOnComplete = value; SaveRuntimeOptions(); }
}
public int ResetDelaySec
{
get => _runtimeOptions.ResetDelaySec;
set { if (!CanChangeSettings || value == ResetDelaySec) return; _runtimeOptions.ResetDelaySec = Math.Max(1, value); SaveRuntimeOptions(); }
}
private bool _accessReady;
/// <summary>保存独立运行参数,供下次启动流程时读取。</summary>
private void SaveRuntimeOptions()
{
_runtimeStore.Save(_runtimeOptions);
RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec));
}
/// <summary>打开所选相机的独立配置窗口</summary>
public DelegateCommand ConfigureCameraCommand { get; private set; } = null!;
/// <summary>刷新相机列表</summary>
public DelegateCommand RefreshCamerasCommand { get; private set; } = null!;
/// <summary>开始 / 停止</summary>
public DelegateCommand StartStopCommand { get; private set; } = null!;
public DelegateCommand ResetCountsCommand { get; private set; } = null!;
public DelegateCommand PlayStandardSopCommand { get; private set; } = null!;
public DelegateCommand DeleteRecipeCommand { get; private set; } = null!;
/// <summary>应用配方</summary>
public DelegateCommand ApplyRecipeCommand { get; private set; } = null!;
/// <summary>快照</summary>
public DelegateCommand SnapshotCommand { get; private set; } = null!;
/// <summary>编辑当前选中的配方(弹窗)</summary>
public DelegateCommand EditRecipeCommand { get; private set; } = null!;
/// <summary>新建配方(弹窗)</summary>
public DelegateCommand NewRecipeCommand { get; private set; } = null!;
public DelegateCommand OpenRecipeFolderCommand { get; private set; } = null!;
/// <summary>把选中配方导出为单个配方包文件</summary>
public DelegateCommand ExportRecipeCommand { get; private set; } = null!;
/// <summary>从配方包导入配方(不自动应用)</summary>
public DelegateCommand ImportRecipeCommand { get; private set; } = null!;
/// <summary>切换选中设备前异步释放当前连接,协调相机忙状态与命令可用性。</summary>
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)));
private void SetCameraBusy(bool busy)
{
_isCameraBusy = busy;
RaisePropertyChanged(nameof(CanSelectCamera)); RaisePropertyChanged(nameof(CanChangeSettings)); RaisePropertyChanged(nameof(CanChangeModels));
RaiseCommands();
}
/// <summary>运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用</summary>
private bool CanEditRecipe() => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe);
private bool CanDeleteRecipe() => CanSelectCamera && !_camera.IsGrabbing && SelectedRecipe is not null && Recipes.Contains(SelectedRecipe);
/// <summary>
/// 刷新所有命令的可用状态。Prism 的 DelegateCommand 只在被显式 raise 时才重估 CanExecute,
/// 绑定上去的按钮不会因属性变化自动亮起来(实测:选了相机"开始/停止"仍灰着)。
/// </summary>
private void RaiseCommands()
{
// 构造函数里 LoadRecipes() 会先设 SelectedRecipe,那时命令还没创建,必须空安全
ConfigureCameraCommand?.RaiseCanExecuteChanged();
RefreshCamerasCommand?.RaiseCanExecuteChanged();
StartStopCommand?.RaiseCanExecuteChanged();
ResetCountsCommand?.RaiseCanExecuteChanged();
PlayStandardSopCommand?.RaiseCanExecuteChanged();
ApplyRecipeCommand?.RaiseCanExecuteChanged();
SnapshotCommand?.RaiseCanExecuteChanged();
EditRecipeCommand?.RaiseCanExecuteChanged();
NewRecipeCommand?.RaiseCanExecuteChanged();
DeleteRecipeCommand?.RaiseCanExecuteChanged();
ImportRecipeCommand?.RaiseCanExecuteChanged();
ExportRecipeCommand?.RaiseCanExecuteChanged();
OpenRecipeFolderCommand?.RaiseCanExecuteChanged();
}
/// <summary>
/// 采集线程:克隆最新帧并合并 UI 刷新请求,避免推理或定时轮询拖慢预览
/// </summary>
/// <remarks>从采集回调克隆预览图,仅保留最新帧;相机原帧在回调结束后由底层释放。</remarks>
private void OnCameraFrame(CameraFrame frame)
{
lock (_frameLock)
{
if (_destroyed || _standardSopCancellation is not null) return;
var clone = frame.Bgr.Clone();
var old = _pending;
_pending = clone;
old?.Dispose();
}
if (Interlocked.Exchange(ref _renderQueued, 1) == 0)
_dispatcher.BeginInvoke(() =>
{
Interlocked.Exchange(ref _renderQueued, 0);
if (!_destroyed && _standardSopCancellation is null) RenderFrame();
}, DispatcherPriority.Render);
}
/// <summary>
/// 快照:把最近处理过的帧连同 ROI 存到 snaps/
/// </summary>
private void Snapshot()
{
var frame = _lastFrame;
if (frame is null) return;
lock (_frameLock)
{
if (_pending is null) return;
if (string.IsNullOrWhiteSpace(ActiveRecipe) || ActiveRecipe == "未应用配方") return;
var dir = Path.Combine(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(ActiveRecipe)), "snaps");
Directory.CreateDirectory(dir);
var path = Path.Combine(dir, $"{frame.FrameId}_{frame.Timestamp:HHmmss_fff}.png");
Cv2.ImWrite(path, _pending);
Log("info", $"快照已存:{path}");
}
}
/// <inheritdoc />
/// <remarks>停止界面定时刷新并解除事件订阅,回收预览及流程显示资源。</remarks>
public override void Destroy()
{
Access.SessionChanged -= AccessChanged;
_statisticsTimer.Stop();
_standardSopCancellation?.Cancel();
_engine.Stop();
_engine.RoundFinished -= OnRoundFinished;
_camera.FrameArrived -= OnCameraFrame;
_pipeline.ResultFrameArrived -= OnResultFrame;
_engine.StepSnapshotChanged -= OnStepSnapshot;
_engine.RoundStarted -= OnRoundStarted;
ClearProcessImages();
lock (_frameLock)
{
_destroyed = true;
_pending?.Dispose();
_pending = null;
}
var previous = Frame as BitmapSource;
Frame = null;
previous?.Dispose();
_bitmap?.Dispose();
_bitmap = null;
// Image writes own their frames and never wait for the UI thread.
_completionImageSaves.GetAwaiter().GetResult();
// 相机与推理管线是应用级共享实例,由 App 中的主窗口 Closed 回调统一释放。
base.Destroy();
}
/// <summary>
/// 从配方工作区读取有效配方,恢复上次选择,并预读标准视频时长。
/// </summary>
private void LoadRecipes(string? preferred = null)
{
if (preferred is null)
{
try
{
if (File.Exists(LastRecipePath)) preferred = JsonSerializer.Deserialize<string>(File.ReadAllText(LastRecipePath));
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException)
{ Log("warn", "读取上次配方选择失败:" + error.Message); }
}
var names = DesktopPlatform.Recipes.Names().Select(name => name + ".yaml").ToList();
foreach (var name in names)
SopHelper.Engine.Recipes.SopStandardVideoDuration.Get(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(name)));
_refreshingRecipes = true;
try
{
// Keep surviving items in place: clearing a hidden ComboBox's source loses
// its selection even when the view model still holds the same recipe.
for (var index = Recipes.Count - 1; index >= 0; index--)
if (!names.Contains(Recipes[index])) Recipes.RemoveAt(index);
for (var index = 0; index < names.Count; index++)
{
var existing = Recipes.IndexOf(names[index]);
if (existing < 0) Recipes.Insert(index, names[index]);
else if (existing != index) Recipes.Move(existing, index);
}
SelectedRecipe = preferred is not null && Recipes.Contains(preferred) ? preferred : Recipes.FirstOrDefault();
RaisePropertyChanged(nameof(SelectedRecipe));
}
finally { _refreshingRecipes = false; }
RememberRecipe(SelectedRecipe);
}
private void RememberRecipe(string? name)
{
// Ignore transient nulls while the selection control refreshes, and invalid selections.
if (string.IsNullOrWhiteSpace(name) || !Recipes.Contains(name)) return;
try
{
Directory.CreateDirectory(Path.GetDirectoryName(LastRecipePath)!);
var temporary = LastRecipePath + ".tmp";
File.WriteAllText(temporary, JsonSerializer.Serialize(name));
File.Move(temporary, LastRecipePath, overwrite: true);
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{ Log("warn", "保存配方选择失败:" + error.Message); }
}
/// <summary>
/// 编辑器保存后:重扫目录(新建的文件要能选到),选中刚存的那个,再重新应用一次
/// </summary>
private void RefreshRecipes(string fileName)
{
LoadRecipes(fileName);
ApplyRecipe();
}
/// <summary>确认后停止相关使用并归档配方目录,再刷新列表和当前状态。</summary>
private async Task DeleteRecipeAsync()
{
if (!CanDeleteRecipe() || SelectedRecipe is not { } fileName) return;
if (ConfirmDeleteRecipeAsync is null) { StatusText = "请在运行设置中确认删除配方"; return; }
_deletingRecipe = true; RaisePropertyChanged(nameof(CanSelectCamera)); RaisePropertyChanged(nameof(CanChangeSettings)); RaisePropertyChanged(nameof(CanChangeModels)); RaiseCommands();
var wasActive = false;
try
{
var name = Path.GetFileNameWithoutExtension(fileName);
if (!await ConfirmDeleteRecipeAsync(name)) { StatusText = "已取消删除配方"; return; }
if (_destroyed || IsRunning || _isCameraBusy || _camera.IsGrabbing) return;
wasActive = ActiveRecipe == fileName;
if (wasActive) ClearActiveRecipe();
var archive = DesktopPlatform.Recipes.Delete(name);
var next = SelectedRecipe == fileName ? null : SelectedRecipe;
LoadRecipes(next);
if (Recipes.Count == 0)
{
if (!wasActive) ClearActiveRecipe();
try { if (File.Exists(LastRecipePath)) File.Delete(LastRecipePath); }
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{ Log("warn", "清除配方选择记录失败:" + error.Message); }
}
StatusText = $"已删除配方“{name}”,数据已移至本地已删除配方目录";
Log("info", $"{StatusText}:{archive}");
}
catch (Exception error)
{
if (wasActive && File.Exists(RecipePath(fileName)))
{
try { ApplyRecipe(); } catch (Exception restoreError) { Log("warn", "恢复配方失败:" + restoreError.Message); }
}
LoadRecipes(SelectedRecipe);
StatusText = "删除配方失败:" + error.Message; Log("warn", StatusText);
}
finally { _deletingRecipe = false; RaisePropertyChanged(nameof(CanSelectCamera)); RaisePropertyChanged(nameof(CanChangeSettings)); RaisePropertyChanged(nameof(CanChangeModels)); RaiseCommands(); }
}
private void ClearActiveRecipe()
{
_pipeline.LoadModels(new PipelineOptions());
_engine.Load(new SopConfig());
ClearProcessImages();
StepCards.Clear(); Rois.Clear(); HandResult = null; _lastFrame = null;
ResetCountsCommand?.RaiseCanExecuteChanged();
PlayStandardSopCommand?.RaiseCanExecuteChanged();
ActiveRecipe = "未应用配方";
RaisePropertyChanged(nameof(InferenceBackendText));
RaiseCommands();
}
/// <summary>
/// 导入配方包:选文件 → 检查包 → 同名时确认覆盖或改名 → 落位并刷新列表。
/// </summary>
/// <remarks>
/// 只新增或替换配方,不改当前已应用配方、不自动应用、不启动采集,现场运行节奏不被打断。
/// 检查阶段先读出包内配方名、文件数与提醒;同名时由设置页弹窗选择覆盖(旧配方整目录归档)或改名导入,取消时盘上文件不动。
/// 只捕获配方包与文件系统的可预期错误并写状态和日志,解压失败不会变成界面崩溃。
/// </remarks>
private async Task ImportRecipeAsync()
{
if (!CanImportRecipe()) return;
var picker = new OpenFileDialog
{
Title = "导入配方包",
Filter = "配方包|*.bwsrecipe;*.zip|所有文件|*.*",
InitialDirectory = UserFileDirectory
};
if (await picker.ShowDialogAsync() != true) return;
var packagePath = picker.FileName;
SetRecipeTransfer(true);
try
{
var info = await Task.Run(() => RecipePackage.Inspect(packagePath));
var target = info.RecipeName;
var overwrite = false;
if (File.Exists(DesktopPlatform.Recipes.ConfigPath(target)))
{
var suggested = RecipePackage.SuggestName(DesktopPlatform.Recipes, target);
var choice = ConfirmImportConflictAsync is null
? ImportConflictChoice.Cancel
: await ConfirmImportConflictAsync(new ImportConflict(packagePath, info, suggested));
switch (choice)
{
case ImportConflictChoice.Overwrite: overwrite = true; break;
case ImportConflictChoice.SaveAsNew: target = suggested; break;
default: StatusText = "已取消导入配方"; return;
}
}
var result = await Task.Run(() => RecipePackage.Import(DesktopPlatform.Recipes, packagePath, target, overwrite));
// 只刷新列表并保持当前选择:新配方要由工艺师核对区域坐标后手动应用,区域是按相机分辨率标定的。
LoadRecipes(SelectedRecipe);
StatusText = $"已导入配方“{result.Name}”({info.FileCount} 个文件,{FormatBytes(info.TotalBytes)}),核对区域后点击“应用”开始使用";
Log("info", StatusText);
foreach (var warning in result.Warnings) Log("warn", warning);
}
catch (Exception error) when (error is IOException or InvalidDataException or ArgumentException or NotSupportedException or JsonException)
{
StatusText = "导入配方失败:" + error.Message;
Log("warn", StatusText);
}
finally { SetRecipeTransfer(false); }
}
/// <summary>导出选中配方为配方包文件,成功后在状态栏给出路径和体积。</summary>
/// <remarks>读配方目录在后台线程执行,不改动配方文件;配方目录之外的完成图目录写进包内说明,导入端同样显示。</remarks>
private async Task ExportRecipeAsync()
{
if (!CanExportRecipe()) return;
var name = Path.GetFileNameWithoutExtension(SelectedRecipe!);
var picker = new SaveFileDialog
{
Title = "导出配方包",
Filter = "配方包|*.bwsrecipe|所有文件|*.*",
DefaultExt = "bwsrecipe",
SuggestedFileName = name,
InitialDirectory = UserFileDirectory
};
if (await picker.ShowDialogAsync() != true) return;
SetRecipeTransfer(true);
try
{
var result = await Task.Run(() => RecipePackage.Export(DesktopPlatform.Recipes, name, picker.FileName));
StatusText = $"已导出配方“{name}”({result.FileCount} 个文件,{FormatBytes(result.TotalBytes)}):{result.Path}";
Log("info", StatusText);
foreach (var note in result.Warnings) Log("warn", note);
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException or ArgumentException)
{
StatusText = "导出配方失败:" + error.Message;
Log("warn", StatusText);
}
finally { SetRecipeTransfer(false); }
}
/// <summary>按现场习惯显示包体积,便于判断能否用 U 盘或即时消息传递。</summary>
private static string FormatBytes(long bytes) => bytes switch
{
>= 1024L * 1024 * 1024 => $"{bytes / 1024.0 / 1024 / 1024:0.0} GB",
>= 1024L * 1024 => $"{bytes / 1024.0 / 1024:0.0} MB",
>= 1024 => $"{bytes / 1024.0:0.0} KB",
_ => $"{bytes} B"
};
/// <summary>配方包默认读写位置:优先下载目录,其次文档目录。</summary>
private static string UserFileDirectory
{
get
{
var downloads = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
return Directory.Exists(downloads) ? downloads : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
}
/// <summary>
/// 编辑当前选中的配方
/// </summary>
private void EditRecipe()
{
var path = RecipePath(SelectedRecipe!);
if (!File.Exists(path))
{
Log("warn", $"配方不存在:{path}");
return;
}
// 编辑器读的是这个已解析的 config(含校验提醒),保存时再整体映射回去
OpenEditor(path, false, SopConfigLoader.Load(path));
}
/// <summary>
/// 新建配方(空白配方,文件名在编辑器里填)
/// </summary>
private void NewRecipe()
{
OpenEditor("", true, new SopConfig());
}
/// <summary>
/// 弹出配方编辑器。每次保存成功后刷新配方列表,编辑窗口保持打开。
/// </summary>
private void OpenEditor(string path, bool isNew, SopConfig config)
{
var parameters = new DialogParameters();
parameters.Add("directory", RecipeDirectory);
parameters.Add("path", path);
parameters.Add("new", isNew);
parameters.Add("config", config);
parameters.Add("onSaved", new Action<string>(fileName =>
_dispatcher.BeginInvoke(() => RefreshRecipes(fileName))));
parameters.Add("cameraService", _camera);
parameters.Add("selectedCameraProvider", new Func<CameraInfo?>(() => SelectedCamera));
parameters.Add("canUseCamera", new Func<bool>(() => CanSelectCamera && !_camera.IsGrabbing));
if (SelectedCamera is not null) parameters.Add("cameraInfo", SelectedCamera);
if (Frame is BitmapSource image)
{
var preview = image.Clone();
preview.Freeze();
parameters.Add("preview", preview);
}
_dialogs.ShowDialog(EditorDialogName, parameters, _ => { });
}
private async Task ConfigureCameraAsync()
{
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 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
{
if (File.Exists(LastCameraPath))
{
_lastUsedCamera = JsonSerializer.Deserialize<CameraInfo>(File.ReadAllText(LastCameraPath));
if (_lastUsedCamera?.Kind != CameraKind.Uvc) _lastUsedCamera = null;
}
}
catch (Exception ex)
{
Log("warn", $"读取上次使用的相机失败:{ex.Message}");
}
}
private void RememberCamera(CameraInfo camera)
{
_lastUsedCamera = camera;
try
{
Directory.CreateDirectory(Path.GetDirectoryName(LastCameraPath)!);
File.WriteAllText(LastCameraPath, JsonSerializer.Serialize(camera));
}
catch (Exception ex)
{
Log("warn", $"保存上次使用的相机失败:{ex.Message}");
}
}
private async Task RefreshCamerasAsync()
{
if (_destroyed || !CanSelectCamera) return;
SetCameraBusy(true);
try
{
var previous = SelectedCamera ?? _lastUsedCamera;
SelectedCamera = null;
Cameras.Clear();
var cameras = await _camera.EnumerateAsync();
if (_destroyed) return;
foreach (var info in cameras)
Cameras.Add(info);
if (Cameras.Count == 0)
{
Log("warn", "没有枚举到 USB(UVC)相机");
if (_camera.IsConnected) await Task.Run(_camera.Disconnect);
return;
}
SelectedCamera = previous is null ? Cameras[0] : Cameras.FirstOrDefault(c => c.IsSameDevice(previous));
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)
{
Log("warn", $"刷新相机失败:{ex.Message}");
}
finally { SetCameraBusy(false); }
}
/// <summary>协调启动/停止的忙状态,避免重复点击同时操作相机与运行引擎。</summary>
private async Task StartStopAsync()
{
if (_isCameraBusy) return;
SetCameraBusy(true);
try { await StartStopCoreAsync(); }
catch (Exception ex)
{
await Task.Run(_camera.Disconnect);
IsRunning = false;
StatusText = "启动失败";
Log("warn", $"相机操作失败:{ex.Message}");
}
finally { SetCameraBusy(false); }
}
/// <summary>按当前运行状态停止或启动;启动时依次应用配方、连接设备、设置参数和开启管线。</summary>
private async Task StartStopCoreAsync()
{
if (_standardSopCancellation is { } video)
{
video.Cancel();
await _standardSopTask;
return;
}
if (IsRunning)
{
await Task.Run(() =>
{
_pipeline.Stop();
// 只停止取帧与处理,保留设备连接供再次开始复用。
});
IsRunning = false;
StatusText = "已停止采集,连接保留";
return;
}
if (SelectedCamera is null)
{
Log("warn", "先选相机");
return;
}
if (string.IsNullOrWhiteSpace(SelectedRecipe))
{
Log("warn", "先选配方");
return;
}
if (!await SopHelper.Models.CameraSettingsStore.Current.ConnectAsync(_camera, SelectedCamera)) return;
ApplyRecipe();
try
{
var mode = await SopHelper.Models.CameraSettingsStore.Current.ApplyAsync(_camera, SelectedCamera);
if (!string.IsNullOrEmpty(mode)) Log("info", mode);
}
catch (Exception ex)
{
Log("error", "设置相机参数失败:" + ex.Message);
await Task.Run(_camera.Disconnect);
StatusText = "设置相机参数失败";
return;
}
// 抽帧从界面参数覆盖配方默认值
_runtimeOptions.Apply(_engine.Config);
_pipeline.SetFrameStride(FrameStride);
if (!await _pipeline.StartAsync())
{
await Task.Run(_camera.Disconnect);
Log("warn", "采集启动失败");
return;
}
_engine.Start();
IsRunning = true;
RememberCamera(SelectedCamera);
StatusText = "运行中";
}
/// <summary>读取所选配方并覆盖独立运行设置,按手部需求加载模型,再重建步骤卡和区域列表。</summary>
private void ApplyRecipe()
{
HandResult = null;
if (string.IsNullOrWhiteSpace(SelectedRecipe)) return;
var path = RecipePath(SelectedRecipe);
if (!File.Exists(path))
{
Log("warn", $"配方不存在:{path}");
return;
}
var config = SopConfigLoader.Load(path);
_runtimeOptions = _runtimeStore.LoadOrMigrate(config);
_runtimeOptions.Apply(config);
RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec));
_engine.Load(config);
var needsHands = config.Sop.Steps.Any(step => ConditionMethod.RequiresHandDetection(step.Detection?.Method));
var options = new PipelineOptions
{
// 文件名必须和 models/ 下实际一致,否则 ResolveModel 返回 null、手部链路静默不跑
PalmModelPath = needsHands ? ResolveModel("models/palm_detection_full_Nx3x192x192_post.onnx") : null,
LandmarkModelPath = needsHands ? ResolveModel("models/hand_landmark_sparse_Nx3x224x224.onnx") : null,
FrameStride = Math.Max(1, config.Sop.Settings.FrameStride),
RequireGpu = OperatingSystem.IsLinux(),
};
try { _pipeline.LoadModels(options); }
finally { RaisePropertyChanged(nameof(InferenceBackendText)); }
ActiveRecipe = SelectedRecipe;
Log("info", $"推理设备:手部={_pipeline.HandBackend},步骤确认={VisionProviderName}");
ClearProcessImages();
StepCards.Clear();
Rois.Clear();
foreach (var step in config.Sop.Steps.OrderBy(s => s.Id))
{
var card = new StepCard { StepId = step.Id, Name = step.Name, Message = "—",
SaveCompletionImage = step.SaveCompletionImage, CompletionImageDirectory = step.CompletionImageDirectory };
UpdateStepCounts(card, _engine.Statistics);
StepCards.Add(card);
}
ResetCountsCommand.RaiseCanExecuteChanged();
PlayStandardSopCommand.RaiseCanExecuteChanged();
foreach (var (name, def) in config.Sop.Regions)
Rois.Add(new RoiItem { Name = name, X = def.X1, Y = def.Y1, W = def.X2 - def.X1, H = def.Y2 - def.Y1, ColorHex = def.Color });
foreach (var warning in config.Warnings)
Log("warn", warning);
Log("info", $"配方已加载:{config.Sop.Name}({StepCards.Count} 步 / {Rois.Count} 区域)");
foreach (var warning in _pipeline.Warnings)
Log("warn", warning);
if (needsHands && (options.PalmModelPath is null || options.LandmarkModelPath is null))
Log("warn", "手部模型缺失,手部检测及画面标记不可用,请检查 models 目录中的 palm / landmark ONNX 文件");
}
/// <summary>
/// 模型路径解析:相对程序目录。不存在返回 null(管线会跳过并记警告)。
/// </summary>
private static string? ResolveModel(string? relative)
{
if (string.IsNullOrWhiteSpace(relative)) return null;
var path = Path.IsPathRooted(relative) ? relative : Path.Combine(AppContext.BaseDirectory, relative);
return File.Exists(path) ? path : null;
}
/// <summary>原图只在管线回调内有效,先克隆再投递 UI;在该帧判定和取证结束后释放克隆。</summary>
private void OnResultFrame(FrameResult result, Mat frame)
{
var videoRound = Volatile.Read(ref _videoRound);
var owned = frame.Clone();
_dispatcher.BeginInvoke(() =>
{
using (owned)
{
// 后台结果可能在切换来源或重播后才到达界面,必须丢弃旧轮次。
if (videoRound != _videoRound || _standardSopCancellation?.IsCancellationRequested == true) return;
_judgementFrame = owned;
try { OnResult(result); }
finally { _judgementFrame = null; }
}
});
}
private void OnRoundStarted()
{
if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) { ClearProcessImages(); RefreshStatistics(); }
else _dispatcher.BeginInvoke(() => { if (!_destroyed) { ClearProcessImages(); RefreshStatistics(); } });
}
private void OnRoundFinished(bool passed) => _dispatcher.BeginInvoke(() => { if (!_destroyed) { StatusText = passed ? "本轮完成,全部通过" : "本轮结束,有步骤未通过并跳过"; RefreshStatistics(); } });
/// <summary>同步轮次、步骤、标准视频时长及累计次数,更新当前步骤的检查窗口进度。</summary>
private void RefreshStatistics()
{
if (_destroyed) return;
var recipe = IsRunning ? ActiveRecipe : SelectedRecipe;
var name = string.IsNullOrWhiteSpace(recipe) ? "" : Path.GetFileNameWithoutExtension(recipe);
var statistics = IsRunning ? _engine.Statistics : _engine.GetStatistics(name);
CompletedCount = statistics.CompletedCount;
FlowElapsedText = FormatDuration(statistics.FlowElapsed);
StepElapsedText = FormatDuration(statistics.StepElapsed);
AverageDurationText = FormatDuration(statistics.AverageDuration);
StandardDurationText = FormatDuration(!string.IsNullOrWhiteSpace(recipe) && Recipes.Contains(recipe)
? SopHelper.Engine.Recipes.SopStandardVideoDuration.Get(DesktopPlatform.Recipes.DirectoryFor(name)) : TimeSpan.Zero);
foreach (var stepCard in StepCards)
{
UpdateStepCounts(stepCard, _engine.Statistics);
UpdateCheckTime(stepCard);
}
if (IsRunning && _engine.CurrentStep is { } step && StepCards.FirstOrDefault(c => c.StepId == step.Id) is { } card)
card.ElapsedText = StepElapsedText;
}
private void ClearProcessImages()
{
foreach (var card in StepCards) { card.CompletionImage = null; card.ElapsedText = FormatDuration(TimeSpan.Zero); }
}
private void OnStepSnapshot(StepSnapshot snapshot)
{
// ProcessFrame 在 UI 线程运行,必须在对应判定帧释放前定格。
if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) UpdateCard(snapshot);
else _dispatcher.BeginInvoke(() => { if (!_destroyed) UpdateCard(snapshot); });
}
/// <summary>在界面线程把推理结果送入状态机,取证回调始终使用本次判定对应的原图。</summary>
private void OnResult(FrameResult result)
{
if (_destroyed || !IsRunning) return;
lock (_frameLock)
{
_lastFrame = result;
}
_engine.ProcessFrame(result, captureDecisionImage: region =>
{
if (_judgementFrame is not { } frame) return [];
return VisionDecisionImage.Encode(frame, region);
});
// 每帧均更新,无检测结果时清除上一帧的手部标记和目标框。
HandResult = result;
InferenceText = $"{(long)(result.InferenceMs / 1000)} 秒";
}
/// <summary>
/// UI 刷新:取采集线程留下的最新帧,不积压历史画面
/// </summary>
private void RenderFrame()
{
Mat? src;
lock (_frameLock)
{
src = _pending;
_pending = null;
}
if (src is null) return;
_frameCount++;
using (src)
{
if (_bitmap is null || _bitmap.PixelWidth != src.Width || _bitmap.PixelHeight != src.Height)
{
_bitmap?.Dispose();
_bitmap = new WriteableBitmap(src.Cols, src.Rows, 96, 96, PixelFormats.Bgr24, null);
// ROI 覆盖层的坐标系就是帧像素坐标系,所以内层 Grid 尺寸必须跟着帧走
FrameWidth = src.Cols;
FrameHeight = src.Rows;
if (HandResult?.Size != (src.Cols, src.Rows)) HandResult = null;
}
_bitmap.WritePixels(new Avalonia.PixelRect(0, 0, src.Cols, src.Rows), src.Data, checked((int)src.Step()));
}
// 同一 IImage 引用不会触发 Avalonia Image 的重绘;覆盖层的局部刷新会留下旧画面。
// 发布独立快照,同时避免渲染线程读取正在写入的位图。
var previous = Frame as BitmapSource;
Frame = _bitmap.Snapshot();
previous?.Dispose();
// 按真实经过的时间统计成功发布的预览帧。
if (_fpsClock.Elapsed.TotalSeconds >= 0.5)
{
FpsText = (_camera.MeasuredCaptureFps is { } captureFps ? $"采集 {captureFps:F1} / " : "")
+ $"渲染 {(_frameCount - _lastTickCount) / _fpsClock.Elapsed.TotalSeconds:F1} fps";
_lastTickCount = _frameCount;
_fpsClock.Restart();
}
}
private readonly RecordedVideoPlayback _standardSop = new();
private CancellationTokenSource? _standardSopCancellation;
private Task _standardSopTask = Task.CompletedTask;
private int _videoRound;
/// <summary>预览区域在视频会话中显示播放器持有的位图,其余时间显示相机位图。</summary>
public ImageSource? PreviewFrame => _standardSopCancellation is null ? Frame : _standardSop.Frame;
public string StandardSopButtonText => _standardSopCancellation is null ? "播放标准 SOP" : "停止标准 SOP";
private string? StandardSopVideoPath => string.IsNullOrWhiteSpace(ActiveRecipe) || ActiveRecipe == "未应用配方" ? null
: Path.Combine(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(ActiveRecipe)), "sop_stand", "sop.avi");
/// <summary>使用当前已应用的配方播放并检测;如果正在采集,先停止相机采集再切换来源。</summary>
private async Task ToggleStandardSopAsync()
{
SetCameraBusy(true);
try
{
if (_standardSopCancellation is not null)
{
await StartStopCoreAsync();
return;
}
if (StandardSopVideoPath is not { } path || !File.Exists(path)) return;
if (IsRunning) await StartStopCoreAsync();
if (_destroyed) return;
var cancellation = new CancellationTokenSource();
_standardSopCancellation = cancellation;
lock (_frameLock)
{
_pending?.Dispose();
_pending = null;
_lastFrame = null;
}
RaisePropertyChanged(nameof(PreviewFrame));
RaisePropertyChanged(nameof(StandardSopButtonText));
_standardSopTask = RunStandardSopAsync(path, cancellation);
}
catch (Exception error) { Log("warn", "切换标准 SOP 视频失败:" + error.Message); }
finally { if (!_destroyed) SetCameraBusy(false); }
}
/// <summary>每次从头播放时启动新检测轮次;片尾留出五秒,并在此期间收尾已提交的判定。</summary>
private async Task RunStandardSopAsync(string path, CancellationTokenSource cancellation)
{
var token = cancellation.Token;
var settings = _engine.Config.Sop.Settings;
var autoReset = settings.AutoResetOnComplete;
TaskCompletionSource end = new(TaskCreationOptions.RunContinuationsAsynchronously);
void PlaybackChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs args)
{
if (args.PropertyName == nameof(RecordedVideoPlayback.IsAtEnd) && _standardSop.IsAtEnd)
end.TrySetResult();
if (args.PropertyName != nameof(RecordedVideoPlayback.Frame) || _destroyed) return;
if (_standardSop.Frame is { } frame)
{
FrameWidth = frame.PixelWidth;
FrameHeight = frame.PixelHeight;
}
RaisePropertyChanged(nameof(PreviewFrame));
}
void PlaybackFailed(string message) => end.TrySetException(new IOException(message));
try
{
// 重播是唯一的自动复位点,避免一次视频播放中途重新开始检测。
settings.AutoResetOnComplete = false;
_pipeline.SetFrameStride(FrameStride);
_standardSop.FrameProcessor = (frame, id, _) => _pipeline.SubmitVideoFrame(frame, id);
_standardSop.PropertyChanged += PlaybackChanged;
_standardSop.Failed += PlaybackFailed;
IsRunning = true;
while (true)
{
token.ThrowIfCancellationRequested();
end = new(TaskCreationOptions.RunContinuationsAsynchronously);
Interlocked.Increment(ref _videoRound);
_lastFrame = null;
HandResult = null;
_engine.Start();
_pipeline.StartVideoInput();
StatusText = "正在播放标准 SOP 并检测";
await _standardSop.PlayAsync(path);
await end.Task.WaitAsync(token);
var pause = Stopwatch.StartNew();
StatusText = "标准 SOP 播放结束,5 秒后重播";
// 等待期间没有新画面,只轮询已提交的 AI 判定,不使用片尾画面重新取证。
while (pause.Elapsed < TimeSpan.FromSeconds(5))
{
var remaining = TimeSpan.FromSeconds(5) - pause.Elapsed;
if (remaining <= TimeSpan.Zero) break;
await Task.Delay(TimeSpan.FromMilliseconds(Math.Min(remaining.TotalMilliseconds, 50)), token);
if (_engine.HasPendingDecision && _lastFrame is { } last) _engine.ProcessFrame(last);
}
_pipeline.StopVideoInput();
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
catch (Exception error) { if (!_destroyed) Log("warn", "标准 SOP 播放或检测失败:" + error.Message); }
finally
{
if (!_destroyed) _pipeline.StopVideoInput();
Interlocked.Increment(ref _videoRound);
_standardSop.PropertyChanged -= PlaybackChanged;
_standardSop.Failed -= PlaybackFailed;
await _standardSop.StopAsync();
_standardSop.FrameProcessor = null;
settings.AutoResetOnComplete = autoReset;
if (!_destroyed)
{
_standardSopCancellation = null;
_lastFrame = null;
IsRunning = false;
if (Frame is BitmapSource cameraFrame)
{
FrameWidth = cameraFrame.PixelWidth;
FrameHeight = cameraFrame.PixelHeight;
}
RaisePropertyChanged(nameof(PreviewFrame));
RaisePropertyChanged(nameof(StandardSopButtonText));
StatusText = token.IsCancellationRequested ? "已停止标准 SOP 播放" : "标准 SOP 播放结束";
}
else _standardSopCancellation = null;
cancellation.Dispose();
}
}
private void ResetCounts()
{
if (StepCards.Count == 0) return;
try
{
_engine.ResetStepCounts();
foreach (var card in StepCards) UpdateStepCounts(card, _engine.Statistics);
Log("info", "已重置当前配方的累计次数:" + ActiveRecipe);
}
catch (Exception error)
{
StatusText = "重置计数失败,累计次数已保留";
Log("warn", "重置计数失败:" + error.Message);
}
}
private static void UpdateStepCounts(StepCard card, SopRunStatistics statistics)
{
var counts = statistics.GetStepCounts(card.StepId);
card.NormalCount = counts.NormalCount;
card.AbnormalCount = counts.AbnormalCount;
}
private void UpdateCheckTime(StepCard card)
{
var progress = _engine.GetCheckWindowProgress(card.StepId);
card.ShowRemainingCheckTime = IsRunning && card.IsCurrent && !card.IsMet && !card.IsSkipped && progress.HasValue;
card.RemainingCheckFraction = progress is { } value ? value.RemainingMs / value.TotalMs : 0;
}
/// <summary>把引擎快照映射为步骤卡状态,并处理完成证据图像的展示和可选保存。</summary>
private void UpdateCard(StepSnapshot snapshot)
{
var card = StepCards.FirstOrDefault(c => c.StepId == snapshot.StepId);
if (card is null) return;
UpdateStepCounts(card, _engine.Statistics);
card.IsCurrent = snapshot.IsCurrent;
card.IsMet = snapshot.IsMet;
card.IsSkipped = snapshot.IsSkipped;
UpdateCheckTime(card);
card.Message = snapshot.Message;
if (snapshot.Elapsed is { } elapsed) card.ElapsedText = FormatDuration(elapsed);
using var aiEvidence = snapshot.IsMet && snapshot.EvidenceJpeg is { } jpeg
? Cv2.ImDecode(jpeg, ImreadModes.Color) : null;
var frame = aiEvidence ?? _judgementFrame;
if (snapshot.IsMet && card.CompletionImage is null && frame is not null && !frame.Empty())
{
card.CompletionImage = BitmapSource.Create(frame.Width, frame.Height, 96, 96,
PixelFormats.Bgr24, null, frame.Data, checked((int)(frame.Step() * frame.Height)), checked((int)frame.Step()));
if (card.SaveCompletionImage) SaveCompletionImage(card, frame);
}
}
private void SaveCompletionImage(StepCard card, Mat frame)
{
try
{
// Resolve against the applied recipe, even if settings has a different pending selection.
var recipeDirectory = DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(ActiveRecipe));
var directory = string.IsNullOrWhiteSpace(card.CompletionImageDirectory)
? Path.Combine(recipeDirectory, "completion-images")
: Path.GetFullPath(card.CompletionImageDirectory.Trim(), recipeDirectory);
var path = Path.Combine(directory, $"{DateTime.Now:yyyyMMdd-HHmmss-fff}-step-{card.StepId}-{Guid.NewGuid():N}.png");
var owned = frame.Clone();
_completionImageSaves = _completionImageSaves.ContinueWith(_ =>
{
using (owned)
{
try
{
Directory.CreateDirectory(directory);
// .NET handles Unicode paths consistently on Windows and Linux.
File.WriteAllBytes(path, owned.ToBytes(".png"));
_dispatcher.BeginInvoke(() => { if (!_destroyed) Log("info", $"步骤 {card.StepId} 结束图已保存:{path}"); });
}
catch (Exception error)
{
_dispatcher.BeginInvoke(() => { if (!_destroyed) Log("warn", $"步骤 {card.StepId} 结束图保存失败:{path};{error.Message}"); });
}
}
}, TaskScheduler.Default);
}
catch (Exception error) { Log("warn", $"步骤 {card.StepId} 结束图保存失败:{error.Message}"); }
}
private void AppendLog(LogEntry entry)
{
Logs.Add(new LogItem { Time = entry.At, Level = entry.Level, Message = entry.Message });
while (Logs.Count > MaxLogLines)
Logs.RemoveAt(0);
}
private void Log(string level, string message)
{
AppendLog(new LogEntry { Level = level, Message = message });
}
}
/// <summary>
/// 步骤卡数据
/// </summary>
public class StepCard : ViewModelBase
{
private bool _showRemainingCheckTime;
private double _remainingCheckFraction;
public bool ShowRemainingCheckTime { get => _showRemainingCheckTime; set => SetProperty(ref _showRemainingCheckTime, value); }
public double RemainingCheckFraction
{
get => _remainingCheckFraction;
set
{
if (!SetProperty(ref _remainingCheckFraction, Math.Clamp(value, 0, 1))) return;
RaisePropertyChanged(nameof(RemainingCheckWidth));
RaisePropertyChanged(nameof(ElapsedCheckWidth));
}
}
public Avalonia.Controls.GridLength RemainingCheckWidth => new(RemainingCheckFraction, Avalonia.Controls.GridUnitType.Star);
public Avalonia.Controls.GridLength ElapsedCheckWidth => new(1 - RemainingCheckFraction, Avalonia.Controls.GridUnitType.Star);
private long _normalCount, _abnormalCount;
public long NormalCount { get => _normalCount; set => SetProperty(ref _normalCount, value); }
public long AbnormalCount { get => _abnormalCount; set => SetProperty(ref _abnormalCount, value); }
private string _elapsedText = "00:00:00";
public string ElapsedText { get => _elapsedText; set => SetProperty(ref _elapsedText, value); }
public bool SaveCompletionImage { get; init; } = true;
public string CompletionImageDirectory { get; init; } = "";
private BitmapSource? _completionImage;
/// <summary>步骤完成时的独立帧,不随实时画面更新。</summary>
public BitmapSource? CompletionImage
{
get => _completionImage;
set
{
var previous = _completionImage;
if (!SetProperty(ref _completionImage, value)) return;
RaisePropertyChanged(nameof(HasCompletionImage));
RaisePropertyChanged(nameof(IsWaitingForImage));
previous?.Dispose();
}
}
public bool HasCompletionImage => CompletionImage is not null;
public bool IsWaitingForImage => !HasCompletionImage;
private bool _isCurrent;
private bool _isMet, _isSkipped;
public bool IsSkipped { get => _isSkipped; set => SetProperty(ref _isSkipped, value); }
private string _message = "";
/// <summary>步骤 Id</summary>
public int StepId { get; set; }
/// <summary>步骤名</summary>
public string Name { get; set; } = "";
/// <summary>当前步骤</summary>
public bool IsCurrent
{
get { return _isCurrent; }
set { SetProperty(ref _isCurrent, value); }
}
/// <summary>已完成</summary>
public bool IsMet
{
get { return _isMet; }
set { SetProperty(ref _isMet, value); }
}
/// <summary>判定说明</summary>
public string Message
{
get { return _message; }
set { SetProperty(ref _message, value); }
}
}
/// <summary>
/// 日志条目
/// </summary>
public class LogItem
{
/// <summary>时刻</summary>
public DateTime Time { get; set; }
/// <summary>级别 info/warn/viol</summary>
public string Level { get; set; } = "info";
/// <summary>文案</summary>
public string Message { get; set; } = "";
}
/// <summary>
/// ROI 覆盖层条目(坐标 = 配方像素坐标,外层 Viewbox 负责缩放)
/// </summary>
public class RoiItem
{
/// <summary>区域名</summary>
public string Name { get; set; } = "";
/// <summary>X</summary>
public double X { get; set; }
/// <summary>Y</summary>
public double Y { get; set; }
/// <summary>W</summary>
public double W { get; set; }
/// <summary>H</summary>
public double H { get; set; }
/// <summary>颜色(#RRGGBB)。不叫 Color——会和 Avalonia.Media.Color 撞名</summary>
public string ColorHex { get; set; } = "#4CAF50";
/// <summary>画刷</summary>
public SolidColorBrush Brush => new((Avalonia.Media.Color)Color.Parse(ColorHex));
}