增加流程完成次数和计时统计并记忆标准录像时长
This commit is contained in:
parent
66a88400ba
commit
95efb21e85
@ -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)
|
||||
|
||||
@ -56,7 +56,7 @@
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="2*" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
@ -73,6 +73,18 @@
|
||||
<TextBlock Text="{Binding FpsText}" Foreground="{StaticResource FgDim}" />
|
||||
</WrapPanel>
|
||||
<TextBlock x:Name="InferenceBackend" Text="{Binding InferenceBackendText}" Margin="0,8,0,0" FontSize="12" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" />
|
||||
<Grid x:Name="RunStatisticsPanel" ColumnDefinitions="Auto,*,Auto,*" RowDefinitions="Auto,Auto,Auto" Margin="0,10,0,0">
|
||||
<TextBlock Text="完成次数" Margin="0,0,8,6" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding CompletedCount}" Foreground="{StaticResource Accent}" />
|
||||
<TextBlock Grid.Column="2" Text="流程计时" Margin="8,0,8,6" />
|
||||
<TextBlock Grid.Column="3" Text="{Binding FlowElapsedText}" />
|
||||
<TextBlock Grid.Row="1" Text="步骤计时" Margin="0,0,8,6" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding StepElapsedText}" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="2" Text="标准用时" Margin="8,0,8,6" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="3" Text="{Binding StandardDurationText}" />
|
||||
<TextBlock Grid.Row="2" Text="平均用时" Margin="0,0,8,0" ToolTip.Tip="完成次数大于10时,显示最近10次完成流程的平均用时" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3" Text="{Binding AverageDurationText}" ToolTip.Tip="完成次数不超过10时为0;停止或重置的未完成流程不参与统计" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<WrapPanel Grid.Row="1" Margin="0,10,0,0" HorizontalAlignment="Left">
|
||||
@ -100,23 +112,28 @@
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Grid.Row="3" Margin="0,10,0,0" Classes="panel">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
|
||||
<StackPanel>
|
||||
<TextBlock Text="步骤" Classes="Title" />
|
||||
<ItemsControl ItemsSource="{Binding StepCards}" Margin="0,8,0,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border x:Name="card" Padding="8,6" Margin="0,0,0,6" Background="{StaticResource Bg}" BorderBrush="{StaticResource Line}" BorderThickness="1" Classes.state5="{Binding IsCurrent}" Classes.state6="{Binding IsCurrent}" Classes="panel">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<StackPanel>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Width="28" FontWeight="Bold" Foreground="{StaticResource FgDim}" Text="{Binding StepId, StringFormat={}{0}.}" />
|
||||
<TextBlock Width="140" Text="{Binding Name}" />
|
||||
<TextBlock Text="{Binding Message}" Foreground="{StaticResource FgDim}" TextTrimming="CharacterEllipsis" />
|
||||
<Rectangle x:Name="dot" Width="8" Height="8" Margin="8,0,0,0" VerticalAlignment="Center" Fill="{StaticResource Ok}" Classes.state4="{Binding IsMet}" IsVisible="False" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding ElapsedText, StringFormat=用时:{0}}" Foreground="{StaticResource FgDim}" FontSize="12" Margin="28,3,0,0" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
<Border Grid.Row="4" Margin="0,10,0,0" Padding="6" Classes="panel">
|
||||
<Grid>
|
||||
|
||||
@ -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();
|
||||
}
|
||||
|
||||
/// <summary>可用相机</summary>
|
||||
@ -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
|
||||
/// <inheritdoc />
|
||||
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
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
@ -49,6 +49,18 @@ public class SopEngine
|
||||
private List<StepDef> _ordered = [];
|
||||
|
||||
private int _index;
|
||||
private int _roundGeneration;
|
||||
private readonly Dictionary<string, SopRunStatistics> _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;
|
||||
|
||||
/// <summary>当前运行状态</summary>
|
||||
@ -84,7 +96,9 @@ public class SopEngine
|
||||
/// </summary>
|
||||
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
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一帧的判定入口(管线回调)
|
||||
/// </summary>
|
||||
@ -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
|
||||
/// </summary>
|
||||
public class StepSnapshot
|
||||
{
|
||||
public TimeSpan? Elapsed { get; set; }
|
||||
/// <summary>步骤 Id</summary>
|
||||
public int StepId { get; set; }
|
||||
|
||||
|
||||
53
src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
Normal file
53
src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
Normal file
@ -0,0 +1,53 @@
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
/// <summary>Session statistics for one recipe; elapsed times exclude pauses.</summary>
|
||||
public sealed class SopRunStatistics(TimeProvider? timeProvider = null)
|
||||
{
|
||||
private readonly TimeProvider _clock = timeProvider ?? TimeProvider.System;
|
||||
private readonly object _gate = new();
|
||||
private readonly Queue<TimeSpan> _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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,59 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace SopHelper.Engine.Training;
|
||||
|
||||
/// <summary>Persistent standard-video duration, read at most once per recipe per process.</summary>
|
||||
public static class SopStandardVideoDuration
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, Lazy<TimeSpan>> 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<TimeSpan>(() => 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<Metadata>(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<TimeSpan>(() => 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); }
|
||||
}
|
||||
}
|
||||
@ -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<SopHelper.Engine.Sop.SopEngine>();
|
||||
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<Grid>().Single(c=>c.Name=="RunStatisticsPanel");
|
||||
var texts=panel.GetVisualDescendants().OfType<TextBlock>().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")!);
|
||||
|
||||
@ -31,6 +31,8 @@ internal static class Program
|
||||
AppBuilder.Configure<Application>().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);
|
||||
|
||||
Loading…
Reference in New Issue
Block a user