From 95efb21e8573e0584068327a0c5cbbb0cf59a841 Mon Sep 17 00:00:00 2001
From: tfarcraw <123211521@163.com>
Date: Tue, 10 Nov 2026 21:30:35 +0800
Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=B5=81=E7=A8=8B=E5=AE=8C?=
=?UTF-8?q?=E6=88=90=E6=AC=A1=E6=95=B0=E5=92=8C=E8=AE=A1=E6=97=B6=E7=BB=9F?=
=?UTF-8?q?=E8=AE=A1=E5=B9=B6=E8=AE=B0=E5=BF=86=E6=A0=87=E5=87=86=E5=BD=95?=
=?UTF-8?q?=E5=83=8F=E6=97=B6=E9=95=BF?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../Training/CameraViewModel.cs | 6 ++
.../VVMs/SopPage/SopPage.axaml | 21 +++++-
.../VVMs/SopPage/SopPageViewModel.cs | 52 ++++++++++++--
.../Sop/SopEngine.cs | 36 +++++++++-
.../Sop/SopRunStatistics.cs | 53 ++++++++++++++
.../Training/SopStandardVideoDuration.cs | 59 ++++++++++++++++
tests/Avalonia.Smoke/Program.cs | 43 ++++++++++++
tests/RecordingLimit.Smoke/Program.cs | 69 +++++++++++++++++++
8 files changed, 331 insertions(+), 8 deletions(-)
create mode 100644 src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
create mode 100644 src/SopHelper.CrossPlatform.Engine/Training/SopStandardVideoDuration.cs
diff --git a/src/SopHelper.Avalonia/Training/CameraViewModel.cs b/src/SopHelper.Avalonia/Training/CameraViewModel.cs
index 030b6fd..6773952 100644
--- a/src/SopHelper.Avalonia/Training/CameraViewModel.cs
+++ b/src/SopHelper.Avalonia/Training/CameraViewModel.cs
@@ -233,6 +233,7 @@ public sealed class CameraViewModel : BindableBase
if (!SopHelper.Engine.Training.RecipeWorkspace.IsWithin(StandardVideoPath, _recipeRecordingDirectory!))
throw new IOException("SOP录像路径不在当前配方目录中");
File.Delete(StandardVideoPath);
+ SopHelper.Engine.Training.SopStandardVideoDuration.Remember(Path.GetDirectoryName(_recipeRecordingDirectory!)!, TimeSpan.Zero);
LastRecording = "";
RecordingInfo = "未录像";
Status = "已清除旧视频,请点击“开始录像”进行重新录制";
@@ -248,6 +249,11 @@ public sealed class CameraViewModel : BindableBase
LastRecording = result.Path;
RecordingInfo = $"已保存 · {result.Duration.TotalSeconds:F1} 秒 · {result.Frames} 帧";
Status = _sopStandard ? "SOP流程视频已保存到当前配方的 sop_stand 目录" : "录像已保存,可在主窗口导入视频继续标注";
+ if (_sopStandard)
+ {
+ try { SopHelper.Engine.Training.SopStandardVideoDuration.Remember(Path.GetDirectoryName(_recipeRecordingDirectory!)!, result.Duration); }
+ catch (Exception error) { Status += ";标准用时记忆保存失败:" + error.Message; }
+ }
}
}
private void OnFrame(CameraFrame frame)
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
index 3af654d..7644075 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
@@ -56,7 +56,7 @@
-
+
@@ -73,6 +73,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
@@ -100,23 +112,28 @@
+
-
+
+
+
+
+
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index 73f1e88..d55bab9 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -45,6 +45,16 @@ public class SopPageViewModel : ViewModelBase
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.0", _stepElapsedText = "00:00:00.0";
+ private string _standardDurationText = "00:00:00.0", _averageDurationText = "00:00:00.0";
+ 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}.{duration.Milliseconds / 100}";
private int _renderQueued;
@@ -116,7 +126,7 @@ public class SopPageViewModel : ViewModelBase
_engine.ViolationRaised += violation => _dispatcher.BeginInvoke(() => AppendViolation(violation));
_engine.StepSnapshotChanged += OnStepSnapshot;
_engine.RoundStarted += OnRoundStarted;
- _engine.Completed += () => _dispatcher.BeginInvoke(() => StatusText = "本轮完成");
+ _engine.Completed += OnCompleted;
LoadRecipes();
@@ -139,6 +149,10 @@ public class SopPageViewModel : ViewModelBase
StatusText = "就绪,请确认运行设置后开始";
LoadLastCamera();
_ = RefreshCamerasAsync();
+ _statisticsTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
+ _statisticsTimer.Tick += (_, _) => RefreshStatistics();
+ _statisticsTimer.Start();
+ RefreshStatistics();
}
/// 可用相机
@@ -181,6 +195,7 @@ public class SopPageViewModel : ViewModelBase
if (!SetProperty(ref _selectedRecipe, value)) return;
if (!_refreshingRecipes) RememberRecipe(value);
RaiseCommands();
+ RefreshStatistics();
}
}
@@ -236,9 +251,10 @@ public class SopPageViewModel : ViewModelBase
set
{
if (!SetProperty(ref _isRunning, value)) return;
- if (!value) HandResult = null;
+ if (!value) { HandResult = null; _engine.Stop(); }
RaisePropertyChanged(nameof(CanSelectCamera));
RaiseCommands();
+ RefreshStatistics();
}
}
@@ -394,6 +410,9 @@ public class SopPageViewModel : ViewModelBase
///
public override void Destroy()
{
+ _statisticsTimer.Stop();
+ _engine.Stop();
+ _engine.Completed -= OnCompleted;
_camera.FrameArrived -= OnCameraFrame;
_pipeline.ResultFrameArrived -= OnResultFrame;
_engine.StepSnapshotChanged -= OnStepSnapshot;
@@ -436,6 +455,8 @@ public class SopPageViewModel : ViewModelBase
{ Log("warn", "读取上次配方选择失败:" + error.Message); }
}
var names = DesktopPlatform.Recipes.Names().Select(name => name + ".yaml").ToList();
+ foreach (var name in names)
+ SopHelper.Engine.Training.SopStandardVideoDuration.Get(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(name)));
_refreshingRecipes = true;
try
{
@@ -817,13 +838,31 @@ public class SopPageViewModel : ViewModelBase
private void OnRoundStarted()
{
- if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) ClearProcessImages();
- else _dispatcher.BeginInvoke(() => { if (!_destroyed) ClearProcessImages(); });
+ if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) { ClearProcessImages(); RefreshStatistics(); }
+ else _dispatcher.BeginInvoke(() => { if (!_destroyed) { ClearProcessImages(); RefreshStatistics(); } });
+ }
+
+ private void OnCompleted() => _dispatcher.BeginInvoke(() => { if (!_destroyed) { StatusText = "本轮完成"; RefreshStatistics(); } });
+
+ 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.Training.SopStandardVideoDuration.Get(DesktopPlatform.Recipes.DirectoryFor(name)) : TimeSpan.Zero);
+ 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;
+ foreach (var card in StepCards) { card.CompletionImage = null; card.ElapsedText = FormatDuration(TimeSpan.Zero); }
}
private void OnStepSnapshot(StepSnapshot snapshot)
@@ -905,6 +944,7 @@ public class SopPageViewModel : ViewModelBase
card.IsCurrent = snapshot.IsCurrent;
card.IsMet = snapshot.IsMet;
card.Message = snapshot.Message;
+ if (snapshot.Elapsed is { } elapsed) card.ElapsedText = FormatDuration(elapsed);
if (snapshot.IsMet && card.CompletionImage is null && _judgementFrame is { } frame)
{
card.CompletionImage = BitmapSource.Create(frame.Width, frame.Height, 96, 96,
@@ -978,6 +1018,8 @@ public class SopPageViewModel : ViewModelBase
///
public class StepCard : ViewModelBase
{
+ private string _elapsedText = "00:00:00.0";
+ public string ElapsedText { get => _elapsedText; set => SetProperty(ref _elapsedText, value); }
public bool SaveCompletionImage { get; init; } = true;
public string CompletionImageDirectory { get; init; } = "";
private BitmapSource? _completionImage;
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
index a449eb7..02605a9 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
@@ -49,6 +49,18 @@ public class SopEngine
private List _ordered = [];
private int _index;
+ private int _roundGeneration;
+ private readonly Dictionary _statistics = new(StringComparer.OrdinalIgnoreCase);
+ public SopRunStatistics Statistics { get; private set; } = new();
+ public SopRunStatistics GetStatistics(string recipeName)
+ {
+ lock (_statistics)
+ {
+ if (!_statistics.TryGetValue(recipeName, out var statistics))
+ _statistics[recipeName] = statistics = new SopRunStatistics();
+ return statistics;
+ }
+ }
private DateTime _stepEnteredAt = DateTime.Now;
/// 当前运行状态
@@ -84,7 +96,9 @@ public class SopEngine
///
public void Load(SopConfig config)
{
+ Stop();
_config = config;
+ Statistics = GetStatistics(config.Sop.Name);
_regions.Clear();
foreach (var (name, def) in config.Sop.Regions)
@@ -122,6 +136,8 @@ public class SopEngine
_evaluator.NoteStepEntered(_ordered[0].Id, _stepEnteredAt);
State = EngineState.Running;
+ Interlocked.Increment(ref _roundGeneration);
+ Statistics.StartRound();
RoundStarted?.Invoke();
Log("info", $"开始运行:{_config.Sop.Name}({_ordered.Count} 步)");
ClearStepStates();
@@ -133,6 +149,7 @@ public class SopEngine
///
public void Reset()
{
+ if (_ordered.Count == 0) return;
_evaluator.Reset();
_violations.Reset();
@@ -141,6 +158,8 @@ public class SopEngine
if (StepAt(0) is StepDef first) _evaluator.NoteStepEntered(first.Id, _stepEnteredAt);
State = EngineState.Running;
+ Interlocked.Increment(ref _roundGeneration);
+ Statistics.StartRound();
RoundStarted?.Invoke();
Log("info", "已复位");
ClearStepStates();
@@ -155,15 +174,24 @@ public class SopEngine
if (State == EngineState.Running)
{
State = EngineState.Paused;
+ Statistics.Pause();
Log("info", "已暂停");
}
else if (State == EngineState.Paused)
{
State = EngineState.Running;
+ Statistics.Resume();
Log("info", "已继续");
}
}
+ public void Stop()
+ {
+ Interlocked.Increment(ref _roundGeneration);
+ Statistics.Stop();
+ State = EngineState.Idle;
+ }
+
///
/// 一帧的判定入口(管线回调)
///
@@ -195,6 +223,7 @@ public class SopEngine
IsCurrent = true,
IsMet = result.IsMet,
Message = result.Message,
+ Elapsed = Statistics.StepElapsed,
};
StepSnapshotChanged?.Invoke(snapshot);
@@ -209,6 +238,7 @@ public class SopEngine
if (_index >= _ordered.Count)
{
State = EngineState.Completed;
+ Statistics.CompleteRound();
Log("info", "★ 全部步骤完成");
ClearStepStates();
Completed?.Invoke();
@@ -216,14 +246,16 @@ public class SopEngine
if (_config.Sop.Settings.AutoResetOnComplete)
{
// 停留一会儿让操作员看到结果,再自动复位
+ var generation = Volatile.Read(ref _roundGeneration);
Task.Delay(TimeSpan.FromSeconds(Math.Max(1, _config.Sop.Settings.ResetDelaySec)))
- .ContinueWith(_ => Reset());
+ .ContinueWith(_ => { if (generation == Volatile.Read(ref _roundGeneration) && State == EngineState.Completed) Reset(); });
}
return;
}
_stepEnteredAt = DateTime.Now;
+ Statistics.NextStep();
_evaluator.NoteStepEntered(_ordered[_index].Id, _stepEnteredAt);
NotifyCurrent();
}
@@ -258,6 +290,7 @@ public class SopEngine
IsCurrent = true,
IsMet = false,
Message = State == EngineState.Running ? "等待判定…" : "已复位",
+ Elapsed = Statistics.StepElapsed,
});
}
@@ -272,6 +305,7 @@ public class SopEngine
///
public class StepSnapshot
{
+ public TimeSpan? Elapsed { get; set; }
/// 步骤 Id
public int StepId { get; set; }
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
new file mode 100644
index 0000000..6580bce
--- /dev/null
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
@@ -0,0 +1,53 @@
+namespace SopHelper.Engine.Sop;
+
+/// Session statistics for one recipe; elapsed times exclude pauses.
+public sealed class SopRunStatistics(TimeProvider? timeProvider = null)
+{
+ private readonly TimeProvider _clock = timeProvider ?? TimeProvider.System;
+ private readonly object _gate = new();
+ private readonly Queue _recent = new();
+ private TimeSpan _flow, _step;
+ private long _since;
+ private bool _active, _running;
+ private long _completed;
+ public long CompletedCount { get { lock (_gate) return _completed; } }
+ public TimeSpan FlowElapsed { get { lock (_gate) return _flow + RunningElapsed; } }
+ public TimeSpan StepElapsed { get { lock (_gate) return _step + RunningElapsed; } }
+ public TimeSpan AverageDuration { get { lock (_gate) return _completed > 10 ? TimeSpan.FromTicks((long)_recent.Average(t => t.Ticks)) : TimeSpan.Zero; } }
+ private TimeSpan RunningElapsed => _running ? _clock.GetElapsedTime(_since) : TimeSpan.Zero;
+ private void Accumulate()
+ {
+ var elapsed = RunningElapsed;
+ _flow += elapsed; _step += elapsed; _since = _clock.GetTimestamp();
+ }
+ public void StartRound()
+ {
+ lock (_gate) { _flow = _step = TimeSpan.Zero; _since = _clock.GetTimestamp(); _active = _running = true; }
+ }
+ public void NextStep()
+ {
+ lock (_gate) { Accumulate(); _step = TimeSpan.Zero; }
+ }
+ public void Pause()
+ {
+ lock (_gate) { Accumulate(); _running = false; }
+ }
+ public void Resume()
+ {
+ lock (_gate) { if (_active && !_running) { _since = _clock.GetTimestamp(); _running = true; } }
+ }
+ public void Stop()
+ {
+ lock (_gate) { Accumulate(); _active = _running = false; }
+ }
+ public void CompleteRound()
+ {
+ lock (_gate)
+ {
+ if (!_active) return;
+ Stop(); _completed++;
+ _recent.Enqueue(_flow);
+ while (_recent.Count > 10) _recent.Dequeue();
+ }
+ }
+}
diff --git a/src/SopHelper.CrossPlatform.Engine/Training/SopStandardVideoDuration.cs b/src/SopHelper.CrossPlatform.Engine/Training/SopStandardVideoDuration.cs
new file mode 100644
index 0000000..180a195
--- /dev/null
+++ b/src/SopHelper.CrossPlatform.Engine/Training/SopStandardVideoDuration.cs
@@ -0,0 +1,59 @@
+using System.Collections.Concurrent;
+using System.Text.Json;
+using OpenCvSharp;
+
+namespace SopHelper.Engine.Training;
+
+/// Persistent standard-video duration, read at most once per recipe per process.
+public static class SopStandardVideoDuration
+{
+ private static readonly ConcurrentDictionary> Cache = new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
+ private sealed record Metadata(double DurationMilliseconds);
+ public static TimeSpan Get(string recipeDirectory) => Cache.GetOrAdd(Path.GetFullPath(recipeDirectory), directory => new Lazy(() => Load(directory))).Value;
+ private static TimeSpan Load(string directory)
+ {
+ var metadata = Path.Combine(directory, "sop_stand", "duration.json");
+ try
+ {
+ if (File.Exists(metadata))
+ {
+ var remembered = JsonSerializer.Deserialize(File.ReadAllText(metadata));
+ if (remembered is { DurationMilliseconds: > 0 } && double.IsFinite(remembered.DurationMilliseconds))
+ return TimeSpan.FromMilliseconds(remembered.DurationMilliseconds);
+ }
+ }
+ catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException or OverflowException) { }
+ var path = Path.Combine(directory, "sop_stand", "sop.avi");
+ if (!File.Exists(path)) return TimeSpan.Zero;
+ try
+ {
+ using var video = new VideoCapture(path);
+ var seconds = video.IsOpened() && video.Fps > 0 ? video.FrameCount / video.Fps : 0;
+ if (!double.IsFinite(seconds) || seconds <= 0) return TimeSpan.Zero;
+ var duration = TimeSpan.FromSeconds(seconds);
+ try { Write(directory, duration); }
+ catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
+ return duration;
+ }
+ catch (Exception error) when (error is OpenCVException or IOException or OverflowException) { return TimeSpan.Zero; }
+ }
+ public static void Remember(string recipeDirectory, TimeSpan duration)
+ {
+ var directory = Path.GetFullPath(recipeDirectory);
+ Cache[directory] = new Lazy(() => duration);
+ Write(directory, duration);
+ }
+ private static void Write(string directory, TimeSpan duration)
+ {
+ var folder = Path.Combine(directory, "sop_stand");
+ Directory.CreateDirectory(folder);
+ var path = Path.Combine(folder, "duration.json");
+ var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
+ try
+ {
+ File.WriteAllText(temporary, JsonSerializer.Serialize(new Metadata(duration.TotalMilliseconds)));
+ File.Move(temporary, path, overwrite: true);
+ }
+ finally { if (File.Exists(temporary)) File.Delete(temporary); }
+ }
+}
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index 814495c..8854eb2 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -119,6 +119,7 @@ internal static class Smoke
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");
await CheckProcessImages(app,sop,window);
+ await CheckRuntimeStatistics(app,sop,window);
await CheckCompletionImageSaving(app,sop);
if(_processImagesOnly){_exit=0;return;}
navigation.SelectedIndex=1;await Task.Delay(80);
@@ -653,6 +654,48 @@ internal static class Smoke
}
finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
}
+ private static async Task CheckRuntimeStatistics(App app,SopPageViewModel sop,Window window)
+ {
+ var engine=app.Container.Resolve();
+ var name=Path.GetFileNameWithoutExtension(sop.SelectedRecipe)!;
+ var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
+ SopStandardVideoDuration.Remember(store.DirectoryFor(name),TimeSpan.FromSeconds(3.25));
+ var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;config.Sop.Settings.AutoResetOnComplete=false;
+ for(var id=1;id<=2;id++)config.Sop.Steps.Add(new(){Id=id,Name="计时步骤"+id,SaveCompletionImage=false,Detection=new(){Method="object_present",TargetObject="part",StableFrames=1}});
+ engine.Load(config);sop.StepCards.Clear();foreach(var step in config.Sop.Steps)sop.StepCards.Add(new(){StepId=step.Id,Name=step.Name,SaveCompletionImage=false});
+ var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
+ sop.IsRunning=true;engine.Start();
+ async Task Emit()
+ {
+ using(var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90)))
+ receive.Invoke(sop,[new SopHelper.Engine.Common.FrameResult {Size=(64,48),Detections=[new(){Label="part",Confidence=1}]},frame]);
+ await Task.Delay(40);
+ }
+ try
+ {
+ await Task.Delay(150);
+ Check(sop.FlowElapsedText!="00:00:00.0"&&sop.StepElapsedText!="00:00:00.0","Flow and step displays advance live without requiring a completion");
+ engine.TogglePause();await Task.Delay(120);var paused=sop.FlowElapsedText;await Task.Delay(150);
+ Check(sop.FlowElapsedText==paused,"Runtime timer display remains frozen during pause");engine.TogglePause();
+ for(var round=1;round<=11;round++)
+ {
+ if(round>1)engine.Reset();
+ await Task.Delay(120);await Emit();await Task.Delay(120);await Emit();await Task.Delay(110);
+ Check(sop.CompletedCount==round,"Runtime count updates once after a complete flow");
+ Check(round<=10?sop.AverageDurationText=="00:00:00.0":sop.AverageDurationText!="00:00:00.0","Average display starts only after the eleventh completion");
+ }
+ Check(sop.StandardDurationText=="00:00:03.2","Runtime displays the remembered standard SOP video duration");
+ Check(sop.StepCards.All(c=>c.ElapsedText!="00:00:00.0"),"Completed step cards retain their individual elapsed times");
+ var panel=window.GetVisualDescendants().OfType().Single(c=>c.Name=="RunStatisticsPanel");
+ var texts=panel.GetVisualDescendants().OfType().Select(t=>t.Text).ToArray();
+ Check(texts.Contains("完成次数")&&texts.Contains("流程计时")&&texts.Contains("步骤计时")&&texts.Contains("标准用时")&&texts.Contains("平均用时")&&texts.Contains("11"),"Operator page renders all five statistics and their bound values");
+ Save(window,"runtime-statistics");
+ engine.Reset();await Task.Delay(120);
+ Check(sop.CompletedCount==11&&sop.StepCards.All(c=>c.ElapsedText=="00:00:00.0"||c.StepId==1),"Reset begins new step timing while preserving completed count and history");
+ }
+ finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
+ }
+
private static async Task CheckCompletionImageSaving(App app,SopPageViewModel sop)
{
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
diff --git a/tests/RecordingLimit.Smoke/Program.cs b/tests/RecordingLimit.Smoke/Program.cs
index 65961d6..49476a7 100644
--- a/tests/RecordingLimit.Smoke/Program.cs
+++ b/tests/RecordingLimit.Smoke/Program.cs
@@ -31,6 +31,8 @@ internal static class Program
AppBuilder.Configure().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
Application.Current!.Styles.Add(new FluentTheme());
Application.Current.Styles.Add(new StyleInclude(new Uri("avares://SopHelper.Avalonia/")) { Source = new Uri("avares://SopHelper.Avalonia/Themes/Styles.axaml") });
+ CheckRunStatistics();
+ CheckStandardDuration(root);
Check(VideoRecorder.MaximumDuration == TimeSpan.FromMinutes(5), "Production recording limit is five minutes");
var clock = new ManualClock();
using var camera = new FakeCamera();
@@ -159,6 +161,9 @@ internal static class Program
Check(model.IsPaused && model.IsRecording, "Cancelling replacement preserves an intentionally paused recording");
model.PauseCommand.Execute(); clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit();
model.StopRecordingCommand.Execute(); CheckVideo(model.LastRecording, 2);
+ using (var recordedDuration = new VideoCapture(model.LastRecording))
+ Check(Math.Abs(SopStandardVideoDuration.Get(store.DirectoryFor(config.Sop.Name)).TotalSeconds - recordedDuration.FrameCount / recordedDuration.Fps) < .000001
+ && File.Exists(Path.Combine(store.DirectoryFor(config.Sop.Name), "sop_stand", "duration.json")), "Stopping standard recording remembers its encoded duration excluding pauses");
CheckRecordingButtons(editor, model, false, false);
Check(!model.StartRecordingCommand.CanExecute() && model.RestartCommand.CanExecute(), "Existing video can only be replaced through confirmed re-recording");
var original = File.ReadAllBytes(expectedPath);
@@ -271,6 +276,70 @@ internal static class Program
while (!task.IsCompleted && wait.Elapsed < TimeSpan.FromSeconds(5)) { Dispatcher.UIThread.RunJobs(); Thread.Sleep(1); }
Check(task.IsCompleted, "Camera shutdown completes"); task.GetAwaiter().GetResult();
}
+ private static void CheckRunStatistics()
+ {
+ var clock = new ManualClock(); var statistics = new SopRunStatistics(clock);
+ statistics.StartRound(); clock.Advance(TimeSpan.FromSeconds(2)); statistics.NextStep();
+ clock.Advance(TimeSpan.FromSeconds(3)); statistics.Pause(); clock.Advance(TimeSpan.FromMinutes(1));
+ Check(statistics.FlowElapsed == TimeSpan.FromSeconds(5) && statistics.StepElapsed == TimeSpan.FromSeconds(3), "Flow and current-step timers exclude paused time");
+ statistics.Resume(); clock.Advance(TimeSpan.FromSeconds(1)); statistics.Stop();
+ clock.Advance(TimeSpan.FromSeconds(10)); statistics.CompleteRound();
+ Check(statistics.CompletedCount == 0 && statistics.FlowElapsed == TimeSpan.FromSeconds(6), "Stopping an unfinished round freezes timers without counting a completion");
+ statistics.StartRound(); clock.Advance(TimeSpan.FromSeconds(8)); statistics.StartRound();
+ Check(statistics.CompletedCount == 0 && statistics.FlowElapsed == TimeSpan.Zero && statistics.StepElapsed == TimeSpan.Zero, "Reset discards unfinished round timing without changing the count");
+ for (var seconds = 1; seconds <= 12; seconds++)
+ {
+ statistics.StartRound(); clock.Advance(TimeSpan.FromSeconds(seconds)); statistics.CompleteRound(); statistics.CompleteRound();
+ Check(statistics.CompletedCount == seconds, "Each completed round counts exactly once");
+ if (seconds <= 10) Check(statistics.AverageDuration == TimeSpan.Zero, "Average remains zero through the tenth completion");
+ else Check(statistics.AverageDuration == TimeSpan.FromSeconds(seconds - 4.5), "Average uses only the latest ten completed flow times");
+ }
+ clock.Advance(TimeSpan.FromMinutes(1));
+ Check(statistics.FlowElapsed == TimeSpan.FromSeconds(12), "Completion freezes the final flow timer");
+ var config = new SopConfig(); config.Sop.Name = "计时甲"; config.Sop.Settings.AutoResetOnComplete = false;
+ config.Sop.Steps.Add(new StepDef { Id = 1, Detection = new StepCondition { Method = "object_present", TargetObject = "part", StableFrames = 1 } });
+ config.Sop.Steps.Add(new StepDef { Id = 2, Detection = new StepCondition { Method = "object_present", TargetObject = "part", StableFrames = 1 } });
+ var engine = new SopEngine(); engine.Load(config); engine.Start(); Thread.Sleep(20);
+ var frame = new SopHelper.Engine.Common.FrameResult { Detections = [new() { Label = "part", Confidence = 1 }] };
+ engine.ProcessFrame(frame);
+ Check(engine.CurrentStep?.Id == 2 && engine.Statistics.FlowElapsed > engine.Statistics.StepElapsed && engine.Statistics.CompletedCount == 0, "Engine resets the step timer while preserving the flow timer at a step transition");
+ engine.TogglePause(); var paused = engine.Statistics.FlowElapsed; Thread.Sleep(20);
+ Check(engine.Statistics.FlowElapsed == paused, "Engine pause freezes live statistics");
+ engine.TogglePause(); engine.ProcessFrame(frame); engine.ProcessFrame(frame);
+ Check(engine.Statistics.CompletedCount == 1 && engine.State == EngineState.Completed, "Engine counts completion only when all steps finish");
+ engine.Load(config); engine.Start(); engine.Stop(); engine.ProcessFrame(frame);
+ Check(engine.Statistics.CompletedCount == 1 && engine.State == EngineState.Idle, "Reloading and stopping preserve the session count and prevent further judgement");
+ var other = new SopConfig(); other.Sop.Name = "计时乙"; engine.Load(other);
+ Check(engine.Statistics.CompletedCount == 0 && engine.GetStatistics("计时甲").CompletedCount == 1, "Recipe counts and timing histories remain isolated within the session");
+ config.Sop.Settings.AutoResetOnComplete = true; config.Sop.Settings.ResetDelaySec = 1;
+ engine.Load(config); engine.Start(); engine.ProcessFrame(frame); engine.ProcessFrame(frame); engine.Stop(); Thread.Sleep(1100);
+ Check(engine.State == EngineState.Idle && engine.Statistics.CompletedCount == 2, "Stopping cancels a pending automatic reset without counting another round");
+ }
+ private static void CheckStandardDuration(string root)
+ {
+ var missing = Path.Combine(root, "duration-missing");
+ Check(SopStandardVideoDuration.Get(missing) == TimeSpan.Zero, "A recipe without remembered duration or a video stays at zero");
+ var source = Path.Combine(root, "duration-source"); var folder = Path.Combine(source, "sop_stand");
+ var clock = new ManualClock(); using var recorder = new VideoRecorder(clock);
+ using var frame = new Mat(48, 64, MatType.CV_8UC3, new Scalar(35, 60, 90));
+ var video = recorder.Start(folder, frame, 30, "sop.avi"); clock.Advance(TimeSpan.FromSeconds(1)); recorder.Write(frame); clock.Advance(TimeSpan.FromSeconds(1)); recorder.Stop();
+ Check(SopStandardVideoDuration.Get(source) == TimeSpan.FromSeconds(2), "Missing duration memory is recovered from standard video metadata");
+ Check(File.Exists(Path.Combine(folder, "duration.json")), "Recovered video duration is remembered on disk");
+ var restart = Path.Combine(root, "duration-restart"); Directory.CreateDirectory(Path.Combine(restart, "sop_stand"));
+ File.Copy(Path.Combine(folder, "duration.json"), Path.Combine(restart, "sop_stand", "duration.json"));
+ Check(SopStandardVideoDuration.Get(restart) == TimeSpan.FromSeconds(2), "Positive persisted duration is used without reopening or requiring the video");
+ var zero = Path.Combine(root, "duration-zero"); Directory.CreateDirectory(Path.Combine(zero, "sop_stand"));
+ File.WriteAllText(Path.Combine(zero, "sop_stand", "duration.json"), "{\"DurationMilliseconds\":0}");
+ File.Copy(video, Path.Combine(zero, "sop_stand", "sop.avi"));
+ Check(SopStandardVideoDuration.Get(zero) == TimeSpan.FromSeconds(2), "Zero duration memory triggers one fallback read of the standard video");
+ var damaged = Path.Combine(root, "duration-damaged"); Directory.CreateDirectory(Path.Combine(damaged, "sop_stand"));
+ File.WriteAllText(Path.Combine(damaged, "sop_stand", "duration.json"), "broken"); File.Copy(video, Path.Combine(damaged, "sop_stand", "sop.avi"));
+ Check(SopStandardVideoDuration.Get(damaged) == TimeSpan.FromSeconds(2), "Invalid duration memory falls back to video metadata");
+ Directory.CreateDirectory(Path.Combine(missing, "sop_stand")); File.Copy(video, Path.Combine(missing, "sop_stand", "sop.avi"));
+ Check(SopStandardVideoDuration.Get(missing) == TimeSpan.Zero, "Startup fallback is attempted only once per recipe in a process");
+ SopStandardVideoDuration.Remember(source, TimeSpan.FromSeconds(4));
+ Check(SopStandardVideoDuration.Get(source) == TimeSpan.FromSeconds(4), "Recording updates the cached standard duration immediately");
+ }
private static void PumpFor(int milliseconds)
{
using var cancellation = new CancellationTokenSource(milliseconds);