diff --git a/README.md b/README.md
index f53c221..5d2a69e 100644
--- a/README.md
+++ b/README.md
@@ -57,6 +57,8 @@ pwsh -File tools/Publish-Avalonia.ps1
`--import-recipes 原数据根目录` 可以导入已有配方,`--check-standalone` / `--check-runtime` 检查本地手部模型和使用模拟 AI 的步骤门控,`--check-gpu` 额外要求手部推理使用 GPU;这些本地诊断不代表真实 D3 接口联调成功。
+主界面每个步骤显示正常次数和异常次数:正常完成计入正常,异常跳过计入异常;按配方累计本次运行的结果,复位、停止或重新应用配方不会清零,重启软件后重新统计。
+
## 验证
```powershell
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
index 7ebacdc..c3a2adc 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
@@ -61,7 +61,6 @@
-
@@ -81,17 +80,13 @@
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
@@ -101,25 +96,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -135,7 +111,11 @@
-
+
+
+
+
+
@@ -144,7 +124,7 @@
-
+
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index 9b5a85b..1e8ceef 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -25,7 +25,6 @@ public class SopPageViewModel : ViewModelBase
{
private static readonly System.Net.Http.HttpClient VisionHttp = new() { Timeout = System.Threading.Timeout.InfiniteTimeSpan };
private const int MaxLogLines = 300;
- private const int MaxTopViolations = 3;
/// 配方目录(相对程序目录)
private static string RecipeDirectory => DesktopPlatform.Recipes.RecipesDirectory;
@@ -127,7 +126,6 @@ public class SopPageViewModel : ViewModelBase
// 帧 Mat 只在采集线程的事件存活期内有效(事件返回即被释放),必须当场克隆
_camera.FrameArrived += OnCameraFrame;
_engine.LogArrived += entry => _dispatcher.BeginInvoke(() => AppendLog(entry));
- _engine.ViolationRaised += violation => _dispatcher.BeginInvoke(() => AppendViolation(violation));
_engine.StepSnapshotChanged += OnStepSnapshot;
_engine.RoundStarted += OnRoundStarted;
_engine.RoundFinished += OnRoundFinished;
@@ -175,9 +173,6 @@ public class SopPageViewModel : ViewModelBase
/// 步骤卡
public ObservableCollection StepCards { get; } = [];
- /// Top3 违规
- public ObservableCollection Violations { get; } = [];
-
/// 日志
public ObservableCollection Logs { get; } = [];
public void ReportD3Service(string message, bool error = false)
@@ -850,8 +845,12 @@ public class SopPageViewModel : ViewModelBase
Rois.Clear();
foreach (var step in config.Sop.Steps.OrderBy(s => s.Id))
- StepCards.Add(new StepCard { StepId = step.Id, Name = step.Name, Message = "—",
- SaveCompletionImage = step.SaveCompletionImage, CompletionImageDirectory = step.CompletionImageDirectory });
+ {
+ var card = new StepCard { StepId = step.Id, Name = step.Name, Message = "—",
+ SaveCompletionImage = step.SaveCompletionImage, CompletionImageDirectory = step.CompletionImageDirectory };
+ UpdateStepCounts(card, _engine.Statistics);
+ StepCards.Add(card);
+ }
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 });
@@ -914,6 +913,7 @@ public class SopPageViewModel : ViewModelBase
AverageDurationText = FormatDuration(statistics.AverageDuration);
StandardDurationText = FormatDuration(!string.IsNullOrWhiteSpace(recipe) && Recipes.Contains(recipe)
? SopHelper.Engine.Training.SopStandardVideoDuration.Get(DesktopPlatform.Recipes.DirectoryFor(name)) : TimeSpan.Zero);
+ foreach (var stepCard in StepCards) UpdateStepCounts(stepCard, _engine.Statistics);
if (IsRunning && _engine.CurrentStep is { } step && StepCards.FirstOrDefault(c => c.StepId == step.Id) is { } card)
card.ElapsedText = StepElapsedText;
}
@@ -999,11 +999,19 @@ public class SopPageViewModel : ViewModelBase
}
}
+ private static void UpdateStepCounts(StepCard card, SopRunStatistics statistics)
+ {
+ var counts = statistics.GetStepCounts(card.StepId);
+ card.NormalCount = counts.NormalCount;
+ card.AbnormalCount = counts.AbnormalCount;
+ }
+
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;
@@ -1052,20 +1060,6 @@ public class SopPageViewModel : ViewModelBase
catch (Exception error) { Log("warn", $"步骤 {card.StepId} 结束图保存失败:{error.Message}"); }
}
- private void AppendViolation(ViolationEvent violation)
- {
- Violations.Insert(0, new ViolationItem
- {
- Time = violation.At,
- StepId = violation.StepId,
- Type = violation.Type,
- Message = violation.Message,
- });
-
- while (Violations.Count > MaxTopViolations)
- Violations.RemoveAt(Violations.Count - 1);
- }
-
private void AppendLog(LogEntry entry)
{
Logs.Add(new LogItem { Time = entry.At, Level = entry.Level, Message = entry.Message });
@@ -1085,6 +1079,9 @@ public class SopPageViewModel : ViewModelBase
///
public class StepCard : ViewModelBase
{
+ 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;
@@ -1141,24 +1138,6 @@ public class StepCard : ViewModelBase
}
}
-///
-/// Top3 违规条目
-///
-public class ViolationItem
-{
- /// 时刻
- public DateTime Time { get; set; }
-
- /// 步骤 Id
- public int StepId { get; set; }
-
- /// 类型
- public string Type { get; set; } = "";
-
- /// 文案
- public string Message { get; set; } = "";
-}
-
///
/// 日志条目
///
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
index 3c806a1..6385694 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
@@ -107,7 +107,7 @@ public partial class SopEngine
/// 每帧判定后的步骤状态快照(UI 步骤卡数据源)
public event Action? StepSnapshotChanged;
- /// 违规(Top3 横幅数据源)
+ /// 违规事件
public event Action? ViolationRaised;
/// 日志
@@ -269,6 +269,7 @@ public partial class SopEngine
Elapsed = Statistics.StepElapsed,
};
+ if (result.IsMet || result.IsSkipped) Statistics.RecordStepResult(step.Id, !result.IsSkipped);
StepSnapshotChanged?.Invoke(snapshot);
if (!result.IsMet && !result.IsSkipped) return;
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
index 6580bce..d11e013 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopRunStatistics.cs
@@ -1,11 +1,14 @@
namespace SopHelper.Engine.Sop;
+public readonly record struct StepRunCounts(long NormalCount, long AbnormalCount);
+
/// 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 readonly Dictionary _stepCounts = [];
private TimeSpan _flow, _step;
private long _since;
private bool _active, _running;
@@ -14,6 +17,19 @@ public sealed class SopRunStatistics(TimeProvider? timeProvider = null)
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; } }
+ public StepRunCounts GetStepCounts(int stepId)
+ {
+ lock (_gate) return _stepCounts.GetValueOrDefault(stepId);
+ }
+ internal void RecordStepResult(int stepId, bool normal)
+ {
+ lock (_gate)
+ {
+ var counts = _stepCounts.GetValueOrDefault(stepId);
+ _stepCounts[stepId] = normal ? counts with { NormalCount = counts.NormalCount + 1 }
+ : counts with { AbnormalCount = counts.AbnormalCount + 1 };
+ }
+ }
private TimeSpan RunningElapsed => _running ? _clock.GetElapsedTime(_since) : TimeSpan.Zero;
private void Accumulate()
{
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index aa4381b..70ac7e4 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -87,6 +87,8 @@ internal static class Smoke
var userCameraBefore=File.Exists(userCameraPath)?File.ReadAllBytes(userCameraPath):null;
await Task.Delay(150);
var app=(App)Application.Current!;var window=lifetime.MainWindow!;
+ if(Environment.GetCommandLineArgs().Contains("--step-counts-only"))
+ { await CheckStepCounts(app,window);_exit=0;return; }
if(Environment.GetCommandLineArgs().Contains("--startup-recipe-only"))
{
var model=app.Container.Resolve();
@@ -660,6 +662,67 @@ internal static class Smoke
}
finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
}
+ private static async Task CheckStepCounts(App app,Window window)
+ {
+ var model=app.Container.Resolve();
+ var engine=app.Container.Resolve();
+ var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
+ const string name="步骤次数测试";
+ var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
+ for(var id=1;id<=2;id++)config.Sop.Steps.Add(new(){Id=id,Name="步骤"+id,Description="零件已放好",SaveCompletionImage=false,
+ Detection=new(){Method="time_elapsed",DurationMs=1,StableFrames=1},
+ AiConfirmation=new(){ImageMode="full_frame",EvidenceMode=id==1?"single_frame":"sequence",CheckWindowMs=0}});
+ Directory.CreateDirectory(store.DirectoryFor(name));SopHelper.Engine.Sop.SopConfigLoader.Save(config,store.ConfigPath(name));
+ model.Recipes.Add(name+".yaml");model.SelectedRecipe=name+".yaml";model.ApplyRecipeCommand.Execute();
+ engine.Config.Sop.Settings.AutoResetOnComplete=false;
+ var decision=new UiVisionDecision();engine.VisionDecisionClient=decision;
+ var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
+ async Task Emit()
+ {
+ using(var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90)))
+ receive.Invoke(model,[new SopHelper.Engine.Common.FrameResult{Size=(64,48)},frame]);
+ await Task.Delay(20);
+ }
+ void Counts(long n1,long a1,long n2,long a2,string message)=>Check(
+ model.StepCards[0].NormalCount==n1&&model.StepCards[0].AbnormalCount==a1
+ &&model.StepCards[1].NormalCount==n2&&model.StepCards[1].AbnormalCount==a2,message);
+ model.IsRunning=true;engine.Start();
+ for(var i=0;i<10&&!decision.Called.Task.IsCompleted;i++)await Emit();
+ Check(decision.Called.Task.IsCompleted,"A real engine step submits its decision");
+ await Emit();await Emit();Counts(0,0,0,0,"Waiting and repeated frame snapshots do not increment step counts");
+ decision.Result.SetResult(new(true,.99,"确认完成"));
+ for(var i=0;i<10&&engine.CurrentStep?.Id==1;i++)await Emit();
+ Counts(1,0,0,0,"A completed step increments only its normal count");
+ await Emit();Counts(1,0,0,1,"An abnormally skipped step increments only its abnormal count");
+ for(var i=0;i<3;i++)await Emit();Counts(1,0,0,1,"Completed rounds and repeated frames do not duplicate counts");
+ engine.Reset();await Task.Delay(30);Counts(1,0,0,1,"Reset preserves per-step totals");
+ decision=new UiVisionDecision();engine.VisionDecisionClient=decision;
+ for(var i=0;i<10&&!decision.Called.Task.IsCompleted;i++)await Emit();
+ engine.Stop();model.IsRunning=false;await Task.Delay(120);
+ Counts(1,0,0,1,"Stopping an unfinished step does not count as an abnormal result");
+ model.ApplyRecipeCommand.Execute();await Task.Delay(30);Counts(1,0,0,1,"Reapplying a recipe restores the counts on rebuilt cards");
+ model.SelectedRecipe="demo.yaml";await Task.Delay(120);Counts(1,0,0,1,"Pending recipe selection does not change the active cards' totals");
+ model.ApplyRecipeCommand.Execute();await Task.Delay(120);
+ Check(model.StepCards.All(c=>c.NormalCount==0&&c.AbnormalCount==0),"Another recipe has independent step totals");
+ model.SelectedRecipe=name+".yaml";model.ApplyRecipeCommand.Execute();await Task.Delay(30);Counts(1,0,0,1,"Returning to the recipe restores its own totals");
+ decision=new UiVisionDecision();engine.VisionDecisionClient=decision;engine.Config.Sop.Settings.AutoResetOnComplete=false;
+ model.IsRunning=true;engine.Start();
+ for(var i=0;i<10&&!decision.Called.Task.IsCompleted;i++)await Emit();
+ decision.Result.SetResult(new(true,.99,"确认完成"));
+ for(var i=0;i<10&&engine.State!=SopHelper.Engine.Sop.EngineState.Completed;i++)await Emit();
+ Counts(2,0,0,2,"Later rounds accumulate each final step result exactly once");
+ var view=window.GetVisualDescendants().OfType().Single();
+ var texts=view.GetVisualDescendants().OfType().Select(t=>t.Text).ToArray();
+ Check(!texts.Contains("违规 Top3")&&!texts.Contains("完成次数")&&!texts.Contains("平均用时"),"Removed summary and violation panels are absent");
+ Check(texts.Count(t=>t?.StartsWith("正常次数:")==true)==2&&texts.Count(t=>t?.StartsWith("异常次数:")==true)==2
+ &&texts.Contains("正常次数:2")&&texts.Contains("异常次数:2"),"Every step card renders its bound normal and abnormal counts");
+ window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;await Task.Delay(80);window.UpdateLayout();
+ var screenshots=Path.GetFullPath(Path.Combine("..","scratch","screenshots"));Directory.CreateDirectory(screenshots);
+ using(var rendered=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height)))
+ {rendered.Render(window);rendered.Save(Path.Combine(screenshots,"step-result-counts.png"));}
+ engine.Stop();model.IsRunning=false;
+ }
+
private static async Task CheckRuntimeStatistics(App app,SopPageViewModel sop,Window window)
{
var engine=app.Container.Resolve();
@@ -694,7 +757,7 @@ internal static class Smoke
Check(sop.StepCards.All(c=>System.Text.RegularExpressions.Regex.IsMatch(c.ElapsedText,@"^\d{2,}:\d{2}:\d{2}$")),"Completed step cards display elapsed times to whole seconds");
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");
+ Check(texts.Contains("流程计时")&&texts.Contains("步骤计时")&&texts.Contains("标准用时")&&!texts.Contains("完成次数")&&!texts.Contains("平均用时"),"Operator page renders timing fields without the removed summary counts");
Save(window,"runtime-statistics");
engine.Reset();await Task.Delay(120);
Check(sop.CompletedCount==11&&sop.StepCards.All(c=>c.ElapsedText=="00:00:00"||c.StepId==1),"Reset begins new step timing while preserving completed count and history");