结束图统一归档到当前配方目录
This commit is contained in:
parent
f7ebe824bb
commit
f107a3fdca
@ -48,7 +48,9 @@ SOP 日志显示驱动回读采集模式,状态栏分别显示 USB 实测采
|
||||
|
||||
Windows DirectShow 设置分辨率时可能把 MJPG 重置为 YUY2,因此程序在分辨率和帧率设置后再应用视频格式;Linux V4L2 保持先设置格式。2026-11-18 在 USB Camera(0c45:636d)上验证:原顺序在 640×480 和 800×600 下均约 15fps,修复后通过实际 UvcCameraService 采集均约 30fps,格式回读为 MJPG,手动曝光回读 15.625ms。设置接口返回成功和驱动回读 30fps 均不能代替实际采集计数。
|
||||
|
||||
SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配方的 `sop_stand` 目录。主界面的“播放标准 SOP”在主预览区播放当前已应用配方的视频,检测流程使用视频帧,每次播完间隔 5 秒从头重播并开始新一轮检测。播放前会停止正在进行的相机采集。配方导入导出在“运行设置”的配方行:选中配方点击“导出”,把配方定义和标准 SOP 视频打包成单个 `.bwsrecipe` 文件(zip,含 `package.json` 清单:配方名、导出时间、导出程序版本、每个文件的大小和 SHA-256)。关键帧已内联在配方 YAML 中,包内只有配方文件和 `sop_stand` 视频,不带运行图片、录像和已移除功能遗留的数据集/模型。步骤的完成图目录若位于配方目录内会改写为相对路径;位于配方目录之外时导出提醒并在包内清空,导入端使用配方默认目录,不搬运工位本地路径。
|
||||
SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配方的 `sop_stand` 目录。主界面的“播放标准 SOP”在主预览区播放当前已应用配方的视频,检测流程使用视频帧,每次播完间隔 5 秒从头重播并开始新一轮检测。播放前会停止正在进行的相机采集。配方导入导出在“运行设置”的配方行:选中配方点击“导出”,把配方定义和标准 SOP 视频打包成单个 `.bwsrecipe` 文件(zip,含 `package.json` 清单:配方名、导出时间、导出程序版本、每个文件的大小和 SHA-256)。关键帧已内联在配方 YAML 中,包内只有配方文件和 `sop_stand` 视频,不带运行图片、录像和已移除功能遗留的数据集/模型。
|
||||
|
||||
每轮检测开始时,在当前配方的 `completion-images` 下创建轮次目录。开启“保存结束图”的步骤通过后,将判定图片以步骤名保存到本轮目录。
|
||||
|
||||
“导入”选择配方包后先检查:清单缺失、包被改动、大小与清单不符、格式版本高于当前程序或包含越界路径都会拒绝并给出原因。同名配方弹窗选择覆盖(现有配方整目录移入 `workspace/deleted-recipes`,可找回)或另存为 `-2` 等新名称;取消不动盘上文件。导入解压到配方目录内的暂存目录,逐文件校验通过后整目录一次移动到位,中断不会留下半个配方,也不留 `.importing-*`。导入的新配方不会自动应用,区域坐标按相机分辨率标定,需要复核后手动点击“应用”。导入导出不需要登录以外的额外权限:操作员点击只弹出权限提示,工艺师和管理员可用。
|
||||
|
||||
|
||||
@ -409,7 +409,6 @@ public class RecipeNode : EditorNode
|
||||
Timeout = step.Timeout,
|
||||
StandardDurationMs = step.StandardDurationMs,
|
||||
SaveCompletionImage = step.SaveCompletionImage,
|
||||
CompletionImageDirectory = step.CompletionImageDirectory,
|
||||
AiConfirmation = step.AiConfirmation is null ? null : new AiConfirmation
|
||||
{
|
||||
MinConfidence = step.AiConfirmation.MinConfidence,
|
||||
@ -476,7 +475,6 @@ public class RecipeNode : EditorNode
|
||||
Timeout = step.Timeout,
|
||||
StandardDurationMs = step.StandardDurationMs,
|
||||
SaveCompletionImage = step.SaveCompletionImage,
|
||||
CompletionImageDirectory = step.CompletionImageDirectory,
|
||||
AiConfirmation = new AiConfirmation
|
||||
{
|
||||
MinConfidence = step.AiMinConfidence,
|
||||
@ -747,7 +745,6 @@ public class StepNode : EditorNode
|
||||
private int _timeout;
|
||||
private int _standardDurationMs;
|
||||
private bool _saveCompletionImage = true;
|
||||
private string _completionImageDirectory = "";
|
||||
// 即使 YAML 没有 detection,也保留可编辑对象,供界面写入新选择的方法。
|
||||
private ConditionNode? _detection = new();
|
||||
|
||||
@ -793,18 +790,13 @@ public class StepNode : EditorNode
|
||||
set { SetProperty(ref _standardDurationMs, value); }
|
||||
}
|
||||
|
||||
/// <summary>本步骤通过时是否将判定图写入配方的轮次归档。</summary>
|
||||
public bool SaveCompletionImage
|
||||
{
|
||||
get => _saveCompletionImage;
|
||||
set => SetProperty(ref _saveCompletionImage, value);
|
||||
}
|
||||
|
||||
public string CompletionImageDirectory
|
||||
{
|
||||
get => _completionImageDirectory;
|
||||
set => SetProperty(ref _completionImageDirectory, value);
|
||||
}
|
||||
|
||||
/// <summary>判定条件(method 留空 = 本步不写 detection 节点)</summary>
|
||||
public ConditionNode? Detection
|
||||
{
|
||||
|
||||
@ -254,16 +254,8 @@
|
||||
|
||||
<Expander x:Name="StepAdditionalSettings" Header="结束图、超时与违规" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" Margin="0,4,0,0">
|
||||
<StackPanel Spacing="6">
|
||||
<CheckBox Content="保存结束图" IsChecked="{Binding SaveCompletionImage, Mode=TwoWay}" />
|
||||
<StackPanel IsEnabled="{Binding SaveCompletionImage}" Spacing="6">
|
||||
<!-- 兼容旧配方的步骤目录字段。运行时按步骤顺序选取一个根目录供整轮归档。 -->
|
||||
<TextBox x:Name="CompletionImageDirectoryBox" Text="{Binding CompletionImageDirectory, Mode=TwoWay}" PlaceholderText="默认:配方目录 / completion-images"
|
||||
ToolTip.Tip="整轮共用一个目录,按步骤顺序采用首个已启用保存的自定义目录。" />
|
||||
<Grid ColumnDefinitions="*,8,*">
|
||||
<Button Content="选择目录…" Click="ChooseCompletionImageDirectory" HorizontalAlignment="Stretch" />
|
||||
<Button Grid.Column="2" Content="恢复默认" Click="ResetCompletionImageDirectory" HorizontalAlignment="Stretch" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<CheckBox Content="保存结束图" IsChecked="{Binding SaveCompletionImage, Mode=TwoWay}"
|
||||
ToolTip.Tip="保存在当前配方的 completion-images 目录下。" />
|
||||
<Grid ColumnDefinitions="76,*">
|
||||
<TextBlock Text="超时 / 秒" Classes="Field" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Timeout, Mode=TwoWay}" ToolTip.Tip="0 表示不限时;需启用全局超时检测" />
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
// 配方编辑器视图事件:连接区域绘制、视频定位及关闭确认等需要访问控件的交互。
|
||||
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Platform.Storage;
|
||||
using Avalonia.Threading;
|
||||
using System.ComponentModel;
|
||||
using SopHelper.SopVideo;
|
||||
@ -71,21 +70,6 @@ public partial class RecipeEditor : UserControl
|
||||
_recording.RecordingLimitReached += RecordingLimit;
|
||||
}
|
||||
private async void RecordingLimit(string message) => await ShowNotice("录像时长提示", message, false);
|
||||
private async void ChooseCompletionImageDirectory(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
if (sender is not Button { DataContext: StepNode step } || TopLevel.GetTopLevel(this) is not Window owner) return;
|
||||
try
|
||||
{
|
||||
var folders = await owner.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title = "选择步骤结束图保存目录", AllowMultiple = false });
|
||||
var directory = folders.FirstOrDefault()?.TryGetLocalPath();
|
||||
if (!string.IsNullOrWhiteSpace(directory)) step.CompletionImageDirectory = directory;
|
||||
}
|
||||
catch (Exception error) { await ShowNotice("选择目录失败", error.Message, false); }
|
||||
}
|
||||
private void ResetCompletionImageDirectory(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
if (sender is Button { DataContext: StepNode step }) step.CompletionImageDirectory = "";
|
||||
}
|
||||
private async Task<bool> ShowNotice(string title, string message, bool confirmation)
|
||||
{
|
||||
if (_closing || _dialog is not null || TopLevel.GetTopLevel(this) is not Window owner) return false;
|
||||
|
||||
@ -38,7 +38,7 @@ public sealed class ImportRecipeConflictDialog : Window
|
||||
new TextBlock { Text = "覆盖前会把现有配方整目录(含录像、标注和运行图片)移入本地“已删除配方”目录,必要时可以找回。", Foreground = new SolidColorBrush(Color.FromRgb(240, 83, 60)), TextWrapping = TextWrapping.Wrap },
|
||||
new TextBlock { Text = "导入的配方不会自动应用,请在列表中核对区域坐标后手动应用。", Foreground = new SolidColorBrush(Color.FromRgb(150, 150, 150)), TextWrapping = TextWrapping.Wrap }
|
||||
};
|
||||
// 包内提醒(配方缺步骤、缺标准视频、完成图目录被改写等)在确认前公开,避免用户覆盖后才发现条件不足。
|
||||
// 确认前展示包内提醒,便于操作员核对步骤和标准视频。
|
||||
foreach (var warning in conflict.Info.Warnings.Take(6))
|
||||
details.Add(new TextBlock { Text = "提醒:" + warning, Foreground = new SolidColorBrush(Color.FromRgb(150, 150, 150)), TextWrapping = TextWrapping.Wrap });
|
||||
details.Add(new StackPanel
|
||||
|
||||
@ -745,7 +745,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
}
|
||||
|
||||
/// <summary>导出选中配方为配方包文件,成功后在状态栏给出路径和体积。</summary>
|
||||
/// <remarks>读配方目录在后台线程执行,不改动配方文件;配方目录之外的完成图目录写进包内说明,导入端同样显示。</remarks>
|
||||
/// <remarks>后台读取已保存的配方和标准视频,运行归档留在当前工位。</remarks>
|
||||
private async Task ExportRecipeAsync()
|
||||
{
|
||||
if (!CanExportRecipe()) return;
|
||||
@ -1092,7 +1092,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
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 };
|
||||
SaveCompletionImage = step.SaveCompletionImage };
|
||||
UpdateStepCounts(card, _engine.Statistics);
|
||||
StepCards.Add(card);
|
||||
}
|
||||
@ -1172,10 +1172,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
try
|
||||
{
|
||||
var recipeDirectory = DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(ActiveRecipe));
|
||||
var configured = StepCards.FirstOrDefault(card => card.SaveCompletionImage
|
||||
&& !string.IsNullOrWhiteSpace(card.CompletionImageDirectory))?.CompletionImageDirectory;
|
||||
var root = configured is null ? Path.Combine(recipeDirectory, "completion-images")
|
||||
: Path.GetFullPath(configured.Trim(), recipeDirectory);
|
||||
var root = Path.Combine(recipeDirectory, "completion-images");
|
||||
var timestamp = startedAt.ToString("yyyyMMdd-HHmmss-fff", CultureInfo.InvariantCulture);
|
||||
var directory = Path.Combine(root, timestamp);
|
||||
for (var suffix = 2; Directory.Exists(directory) || File.Exists(directory); suffix++)
|
||||
@ -1577,7 +1574,6 @@ public class StepCard : ViewModelBase
|
||||
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>
|
||||
|
||||
@ -92,8 +92,6 @@ public static class RecipePackage
|
||||
// 读文件再导出:内存里正在编辑的对象不参与打包,避免把未保存的半成品写进包。
|
||||
var config = SopConfigLoader.Load(configPath);
|
||||
config.Sop.Name = name;
|
||||
var notes = new List<string>();
|
||||
NormalizeCompletionDirectories(config, directory, notes);
|
||||
|
||||
// 配方 YAML 先落到临时文件,保证包内格式与程序保存的一致(含兼容迁移),再与标准视频一起压入。
|
||||
var stagedConfig = Path.Combine(Path.GetTempPath(), "bws-recipe-export-" + Guid.NewGuid().ToString("N") + ".yaml");
|
||||
@ -110,9 +108,8 @@ public static class RecipePackage
|
||||
var target = DestinationPath(destination);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
var sizes = entries.ToDictionary(entry => entry.Entry, entry => new FileInfo(entry.Source).Length);
|
||||
// 导出期的处理说明写进清单 notes:导入方(通常是另一台工位)也能看到“哪个步骤的完成图目录被改写/清空”。
|
||||
var manifest = new PackageManifest(FormatId, FormatVersion, name, DateTimeOffset.UtcNow,
|
||||
typeof(RecipePackage).Assembly.GetName().Version?.ToString() ?? "0.0", notes,
|
||||
typeof(RecipePackage).Assembly.GetName().Version?.ToString() ?? "0.0", [],
|
||||
entries.Select(entry => new PackageFile(entry.Entry, sizes[entry.Entry], Sha256File(entry.Source))).ToList());
|
||||
|
||||
// 先写临时包再原子替换:中断只留下 .tmp,不会把上一次的包改成半份。
|
||||
@ -134,7 +131,7 @@ public static class RecipePackage
|
||||
TryDelete(temporary);
|
||||
throw;
|
||||
}
|
||||
return new ExportResult(target, name, entries.Count, sizes.Values.Sum(), notes);
|
||||
return new ExportResult(target, name, entries.Count, sizes.Values.Sum(), []);
|
||||
}
|
||||
finally { TryDelete(stagedConfig); }
|
||||
}
|
||||
@ -151,7 +148,7 @@ public static class RecipePackage
|
||||
if (!File.Exists(packagePath)) throw new FileNotFoundException("配方包不存在", packagePath);
|
||||
using var archive = OpenRead(packagePath);
|
||||
var manifest = ReadManifest(archive);
|
||||
// 导出端记录的处理说明(完成图目录改写等)在导入端原样重现,两边看同一份说明。
|
||||
// 保留旧版本配方包清单中的导出说明。
|
||||
var warnings = new List<string>(manifest.Notes ?? []);
|
||||
var stagedConfig = Path.Combine(Path.GetTempPath(), "bws-recipe-inspect-" + Guid.NewGuid().ToString("N") + ".yaml");
|
||||
try
|
||||
@ -271,31 +268,6 @@ public static class RecipePackage
|
||||
JsonSerializer.Serialize(stream, manifest, ManifestJson);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把步骤的完成图目录改成相对配方目录的路径。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 运行期按 <c>Path.GetFullPath(目录, 配方目录)</c> 解析,相对路径换机器后仍指向配方自己。
|
||||
/// 配方目录之外的绝对路径导入到别的工位只会写到不相干的位置,因此清空并提醒改用配方默认目录:
|
||||
/// 不猜测现场意图,也不把工位本地路径写进可传递的包里。
|
||||
/// </remarks>
|
||||
private static void NormalizeCompletionDirectories(SopConfig config, string recipeDirectory, List<string> warnings)
|
||||
{
|
||||
foreach (var step in config.Sop.Steps)
|
||||
{
|
||||
var value = step.CompletionImageDirectory?.Trim() ?? "";
|
||||
if (value.Length == 0 || !Path.IsPathRooted(value)) continue;
|
||||
var full = Path.GetFullPath(value, recipeDirectory);
|
||||
if (RecipeWorkspace.IsWithin(full, recipeDirectory))
|
||||
{
|
||||
step.CompletionImageDirectory = Path.GetRelativePath(recipeDirectory, full).Replace('\\', '/');
|
||||
continue;
|
||||
}
|
||||
step.CompletionImageDirectory = "";
|
||||
warnings.Add($"步骤 {step.Id}({step.Name})的完成图目录在配方目录之外({full}),导入后改用配方默认目录,请在编辑器确认。");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>解析并校验清单:格式标识、版本、配方名、条目路径安全、大小与包内容逐条一致。</summary>
|
||||
private static PackageManifest ReadManifest(ZipArchive archive)
|
||||
{
|
||||
|
||||
@ -1,7 +1,5 @@
|
||||
// 配方工作区:统一配置与关联数据的目录、导入迁移、路径修正及可回退的删除归档。
|
||||
// 配方工作区:统一管理配方及关联数据的目录、导入迁移和可回退的删除归档。
|
||||
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
namespace SopHelper.Engine.Recipes;
|
||||
@ -73,7 +71,7 @@ public sealed class RecipeWorkspace(string root)
|
||||
Path.GetFullPath(path).StartsWith(Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar,
|
||||
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
|
||||
/// <summary>一次性复制旧数据并修正路径。保留旧文件供回退,后续只使用新目录。</summary>
|
||||
/// <summary>一次性复制旧配方及其关联文件,保留源数据供回退。</summary>
|
||||
public void ImportFrom(string previousRoot)
|
||||
{
|
||||
var previous = new RecipeWorkspace(previousRoot);
|
||||
@ -88,7 +86,6 @@ public sealed class RecipeWorkspace(string root)
|
||||
var stagedConfig = Path.Combine(staging, name + ".yaml");
|
||||
var config = SopConfigLoader.Load(stagedConfig);
|
||||
config.Sop.Name = name;
|
||||
RemapCompletionDirectories(config, source, destination);
|
||||
SopConfigLoader.Save(config, stagedConfig);
|
||||
// 配方文件最后发布,已有活动配方优先。
|
||||
if (Directory.Exists(destination))
|
||||
@ -103,7 +100,7 @@ public sealed class RecipeWorkspace(string root)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从旧的散放目录复制并修正路径。</summary>
|
||||
/// <summary>从旧的散放目录复制配方及标准视频,按工作区目录统一配方名。</summary>
|
||||
/// <remarks>初始化现有配方存储并接入旧目录,保持已存在的活动配方及删除记录的优先级。</remarks>
|
||||
public void Initialize(params string[] legacyConfigDirectories)
|
||||
{
|
||||
@ -135,26 +132,6 @@ public sealed class RecipeWorkspace(string root)
|
||||
File.Move(configPath + ".migrating", configPath);
|
||||
}
|
||||
foreach (var name in Names()) NormalizeName(ConfigPath(name), name);
|
||||
RefreshLocation();
|
||||
}
|
||||
|
||||
private void RefreshLocation()
|
||||
{
|
||||
var marker = Path.Combine(RecipesDirectory, ".location.json");
|
||||
var previous = File.Exists(marker) ? JsonNode.Parse(File.ReadAllText(marker))?["recipesDirectory"]?.GetValue<string>() : null;
|
||||
if (!string.IsNullOrWhiteSpace(previous) && !Path.GetFullPath(previous).Equals(RecipesDirectory, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
foreach (var name in Names())
|
||||
{
|
||||
var path = ConfigPath(name);
|
||||
var config = SopConfigLoader.Load(path);
|
||||
var oldDirectory = Path.Combine(previous, name);
|
||||
if (!RemapCompletionDirectories(config, oldDirectory, DirectoryFor(name))) continue;
|
||||
SopConfigLoader.Save(config, path + ".tmp");
|
||||
File.Move(path + ".tmp", path, true);
|
||||
}
|
||||
}
|
||||
WriteJson(marker,new JsonObject { ["recipesDirectory"] = RecipesDirectory });
|
||||
}
|
||||
|
||||
private static void NormalizeName(string path, string name)
|
||||
@ -179,28 +156,4 @@ public sealed class RecipeWorkspace(string root)
|
||||
CopyTree(child, Path.Combine(destination, Path.GetFileName(child)));
|
||||
}
|
||||
|
||||
/// <summary>仅迁移旧配方目录内的绝对完成图路径,保留相对路径和工位自定义位置。</summary>
|
||||
private static bool RemapCompletionDirectories(SopConfig config, string source, string destination)
|
||||
{
|
||||
var changed = false;
|
||||
foreach (var step in config.Sop.Steps)
|
||||
{
|
||||
var path = step.CompletionImageDirectory;
|
||||
if (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path)) continue;
|
||||
if (Path.GetFullPath(path).Equals(source, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
|
||||
step.CompletionImageDirectory = destination;
|
||||
else if (IsWithin(path, source))
|
||||
step.CompletionImageDirectory = Path.Combine(destination, Path.GetRelativePath(source, path));
|
||||
else continue;
|
||||
changed = true;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private static void WriteJson(string file, JsonNode? node)
|
||||
{
|
||||
var temporary = file + ".tmp";
|
||||
File.WriteAllText(temporary, node?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
|
||||
File.Move(temporary, file, true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -150,12 +150,9 @@ public class StepDef
|
||||
/// <summary>标准节拍毫秒(报表对比用,判定不参与)</summary>
|
||||
public int StandardDurationMs { get; set; }
|
||||
|
||||
/// <summary>步骤完成时保存对应判定帧,旧配方也默认开启。</summary>
|
||||
/// <summary>步骤完成时将对应判定帧保存到当前配方的轮次归档,旧配方默认开启。</summary>
|
||||
public bool SaveCompletionImage { get; set; } = true;
|
||||
|
||||
/// <summary>按步骤顺序取第一个已启用保存的非空目录作为整轮归档根目录,全部留空时使用当前配方的 completion-images 目录。</summary>
|
||||
public string CompletionImageDirectory { get; set; } = "";
|
||||
|
||||
/// <summary>本步判定条件(AND,全部满足才算完成)</summary>
|
||||
public StepCondition? Detection { get; set; }
|
||||
|
||||
|
||||
@ -39,7 +39,7 @@ public static partial class SopConfigLoader
|
||||
.IgnoreUnmatchedProperties()
|
||||
.Build();
|
||||
|
||||
// 旧 model 字段由 IgnoreUnmatchedProperties 跳过;旧触发方法保留给校验提示。
|
||||
// 旧模型与步骤结束图目录字段直接跳过,旧触发方法保留给校验提示。
|
||||
var config = deserializer.Deserialize<SopConfig>(yaml) ?? new SopConfig();
|
||||
|
||||
MigrateStepSettings(config);
|
||||
|
||||
@ -54,7 +54,7 @@ public static class SopDraftConfigBuilder
|
||||
ai.ImageMode = step.ImageMode ?? (previous is null ? VisionImageMode.FixedRegion : ai.ImageMode);
|
||||
ai.ImageRegion = step.ImageRegion ?? (previous is null ? (step.Method == ConditionMethod.HandMove ? step.ToRegion : step.Region) : ai.ImageRegion);
|
||||
return new StepDef { Id = index + 1, Name = step.Name, Description = step.Description, CompletionCriteria = step.ResolveCompletionCriteria(), Timeout = previous?.Timeout ?? 0,
|
||||
SaveCompletionImage = previous?.SaveCompletionImage ?? true, CompletionImageDirectory = previous?.CompletionImageDirectory ?? "",
|
||||
SaveCompletionImage = previous?.SaveCompletionImage ?? true,
|
||||
MustKeep = previous?.MustKeep ?? [], RequiredObjects = previous?.RequiredObjects ?? [], ViolationRules = previous?.ViolationRules ?? [],
|
||||
StandardDurationMs = Math.Max(1, (int)Math.Round((step.EndSeconds - step.StartSeconds) * 1000)),
|
||||
Detection = new() { Method = step.Method, Region = step.Region, FromRegion = step.FromRegion, ToRegion = step.ToRegion,
|
||||
|
||||
@ -1121,8 +1121,7 @@ internal static class Smoke
|
||||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||||
var name="结束图测试";var file=name+".yaml";
|
||||
var selected=sop.SelectedRecipe;
|
||||
var custom=Path.Combine(store.Root,"其它目录","结束图");
|
||||
var blocked=Path.Combine(store.Root,"不能作为目录.txt");File.WriteAllText(blocked,"blocked");
|
||||
var archiveRoot=Path.Combine(store.DirectoryFor(name),"completion-images");
|
||||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
|
||||
config.Sop.Settings.AutoResetOnComplete=false;config.Sop.Settings.StableFrames=1;
|
||||
for(var id=1;id<=4;id++)
|
||||
@ -1131,16 +1130,17 @@ internal static class Smoke
|
||||
config.Sop.Steps.Add(new()
|
||||
{
|
||||
Id=id,Name=id==1?"装配/检查":id==4?"装配_检查":"步骤"+id,SaveCompletionImage=id!=2,
|
||||
Description="零件安装到位",CompletionImageDirectory=id==3?custom:id==4?blocked:"",
|
||||
Description="零件安装到位",
|
||||
Detection=new(){Method="hand_in_region",Region="工位"+id,StableFrames=1,Tolerance=0},
|
||||
AiConfirmation=new(){ImageMode="full_frame",EvidenceMode="single_frame",CheckWindowMs=0}
|
||||
});
|
||||
}
|
||||
var legacy=SopHelper.Engine.Sop.SopConfigLoader.Parse("sop:\n name: legacy\n steps:\n - id: 1\n name: first\n");
|
||||
Check(legacy.Sop.Steps[0].SaveCompletionImage&&legacy.Sop.Steps[0].CompletionImageDirectory=="","Existing recipes default to saving completion images in their own recipe directory");
|
||||
var legacy=SopConfigLoader.Parse("sop:\n name: legacy\n steps:\n - id: 1\n name: first\n completion_image_directory: old-images\n");
|
||||
Check(legacy.Sop.Steps[0].SaveCompletionImage&&!SopConfigLoader.ToYaml(legacy).Contains("completion_image_directory"),
|
||||
"旧配方保留默认保存开关,旧目录配置在重新保存时清理");
|
||||
var node=RecipeNode.From(config,file,false);
|
||||
var roundTrip=SopHelper.Engine.Sop.SopConfigLoader.Parse(SopHelper.Engine.Sop.SopConfigLoader.ToYaml(node.ToConfig()));
|
||||
Check(roundTrip.Sop.Steps[0].SaveCompletionImage&&!roundTrip.Sop.Steps[1].SaveCompletionImage&&roundTrip.Sop.Steps[2].CompletionImageDirectory==custom,"Step image switches and custom Unicode directories survive editor and YAML round trips");
|
||||
Check(roundTrip.Sop.Steps[0].SaveCompletionImage&&!roundTrip.Sop.Steps[1].SaveCompletionImage,"步骤编辑和 YAML 往返保留结束图开关");
|
||||
Directory.CreateDirectory(store.DirectoryFor(name));
|
||||
SopHelper.Engine.Sop.SopConfigLoader.Save(roundTrip,store.ConfigPath(name));
|
||||
var editorVm=new RecipeEditorViewModel();
|
||||
@ -1151,17 +1151,14 @@ internal static class Smoke
|
||||
{
|
||||
editor.FindControl<Expander>("StepAdditionalSettings")!.IsExpanded=true;await Task.Delay(20);
|
||||
var toggle=editor.GetVisualDescendants().OfType<CheckBox>().Single(c=>c.Content?.ToString()=="保存结束图");
|
||||
var directoryBox=editor.GetVisualDescendants().OfType<TextBox>().Single(t=>t.Name=="CompletionImageDirectoryBox");
|
||||
Check(toggle.IsChecked==true&&string.IsNullOrEmpty(directoryBox.Text),"Step editor exposes image saving enabled by default with the recipe directory selected");
|
||||
Check(toggle.IsChecked==true&&editor.FindControl<TextBox>("CompletionImageDirectoryBox") is null
|
||||
&& !editor.GetVisualDescendants().OfType<Button>().Any(button=>button.Content?.ToString() is "选择目录…" or "恢复默认"),
|
||||
"结束图设置仅保留保存开关");
|
||||
toggle.IsChecked=false;await Task.Delay(20);
|
||||
Check(!editorVm.Recipe.SelectedStep!.SaveCompletionImage&&!directoryBox.IsEffectivelyEnabled,"Turning off image saving disables its directory controls");
|
||||
toggle.IsChecked=true;editorVm.Recipe.SelectedStep=editorVm.Recipe.Steps[2];await Task.Delay(20);
|
||||
Check(directoryBox.Text==custom,"Selecting another step restores its own custom image directory");
|
||||
editor.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="恢复默认").RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||||
Check(editorVm.Recipe.SelectedStep.CompletionImageDirectory=="","Restore default clears the step's directory override");
|
||||
directoryBox.Text=custom;editorVm.SaveCommand.Execute();await Task.Delay(20);
|
||||
Check(!editorVm.Recipe.SelectedStep!.SaveCompletionImage,"关闭结束图开关更新当前步骤");
|
||||
toggle.IsChecked=true;editorVm.SaveCommand.Execute();await Task.Delay(20);
|
||||
var saved=SopHelper.Engine.Sop.SopConfigLoader.Load(store.ConfigPath(name));
|
||||
Check(saved.Sop.Steps[0].SaveCompletionImage&&!saved.Sop.Steps[1].SaveCompletionImage&&saved.Sop.Steps[2].CompletionImageDirectory==custom,"Saving the actual step editor persists per-step image settings");
|
||||
Check(saved.Sop.Steps[0].SaveCompletionImage&&!saved.Sop.Steps[1].SaveCompletionImage,"编辑器保存每步的结束图开关");
|
||||
editorVm.Recipe.SelectedStep=editorVm.Recipe.Steps[0];await Task.Delay(20);Save(dialog,"step-completion-image-settings");
|
||||
}
|
||||
finally{await editorVm.ShutdownAsync();dialog.Close();}
|
||||
@ -1201,8 +1198,8 @@ internal static class Smoke
|
||||
engine.Config.Sop.Settings.AutoResetOnComplete=true;
|
||||
engine.Config.Sop.Settings.ResetDelaySec=1;
|
||||
sop.IsRunning=true;engine.Start();
|
||||
// 第一帧之前就应有空目录。待应用的配方和后续步骤的目录配置都不能改变本轮路径。
|
||||
var first=Directory.GetDirectories(custom).Single();
|
||||
// 第一帧之前就应有空目录,待应用的配方不能改变本轮路径。
|
||||
var first=Directory.GetDirectories(archiveRoot).Single();
|
||||
Check(DateTime.TryParseExact(Path.GetFileName(first),"yyyyMMdd-HHmmss-fff",System.Globalization.CultureInfo.InvariantCulture,
|
||||
System.Globalization.DateTimeStyles.None,out _)&&Directory.GetFiles(first).Length==0,"开始检测时即创建日期时间目录");
|
||||
sop.SelectedRecipe=selected;
|
||||
@ -1219,35 +1216,34 @@ internal static class Smoke
|
||||
}
|
||||
CheckRoundImages(first);
|
||||
Check(sop.StepCards[1].HasCompletionImage,"关闭保存的步骤仍显示完成图片");
|
||||
for(var attempt=0;attempt<100&&Directory.GetDirectories(custom).Length==1;attempt++)await Task.Delay(20);
|
||||
var second=Directory.GetDirectories(custom).Single(path=>path!=first);
|
||||
for(var attempt=0;attempt<100&&Directory.GetDirectories(archiveRoot).Length==1;attempt++)await Task.Delay(20);
|
||||
var second=Directory.GetDirectories(archiveRoot).Single(path=>path!=first);
|
||||
Check(Directory.GetFiles(second).Length==0&&engine.State==EngineState.Running,"自动复位在新一轮首帧之前创建空目录");
|
||||
engine.Config.Sop.Settings.AutoResetOnComplete=false;
|
||||
await Round();
|
||||
CheckRoundImages(first);
|
||||
CheckRoundImages(second);
|
||||
|
||||
// 把原先次选的无效路径提升为归档根目录,确认创建失败时仍可完成检测。
|
||||
// 用同名文件阻挡新配方创建归档根目录,确认检测仍可完成。
|
||||
sop.IsRunning=false;
|
||||
roundTrip.Sop.Steps[2].CompletionImageDirectory="";
|
||||
SopHelper.Engine.Sop.SopConfigLoader.Save(roundTrip,store.ConfigPath(name));
|
||||
sop.SelectedRecipe=file;sop.ApplyRecipeCommand.Execute();
|
||||
engine.Config.Sop.Settings.AutoResetOnComplete=false;
|
||||
sop.IsRunning=true;engine.Start();
|
||||
await Round();
|
||||
Check(engine.State==EngineState.Completed&&sop.Logs.Any(l=>l.Message.Contains("本轮结束图目录创建失败")),"归档目录创建失败有日志,检测继续完成");
|
||||
CheckRoundImages(second);
|
||||
Check(Directory.GetDirectories(custom).Length==2,"创建失败的轮次不会写入上一轮目录");
|
||||
|
||||
sop.IsRunning=false;
|
||||
roundTrip.Sop.Steps[3].CompletionImageDirectory="";
|
||||
SopHelper.Engine.Sop.SopConfigLoader.Save(roundTrip,store.ConfigPath(name));
|
||||
sop.ApplyRecipeCommand.Execute();
|
||||
engine.Config.Sop.Settings.AutoResetOnComplete=false;
|
||||
sop.IsRunning=true;engine.Start();
|
||||
var defaultRound=Directory.GetDirectories(Path.Combine(store.DirectoryFor(name),"completion-images")).Single();
|
||||
await Round();
|
||||
CheckRoundImages(defaultRound);
|
||||
var blockedName=name+"失败";
|
||||
var blockedFile=blockedName+".yaml";
|
||||
roundTrip.Sop.Name=blockedName;
|
||||
Directory.CreateDirectory(store.DirectoryFor(blockedName));
|
||||
SopConfigLoader.Save(roundTrip,store.ConfigPath(blockedName));
|
||||
File.WriteAllText(Path.Combine(store.DirectoryFor(blockedName),"completion-images"),"blocked");
|
||||
sop.Recipes.Add(blockedFile);
|
||||
try
|
||||
{
|
||||
sop.SelectedRecipe=blockedFile;sop.ApplyRecipeCommand.Execute();
|
||||
engine.Config.Sop.Settings.AutoResetOnComplete=false;
|
||||
sop.IsRunning=true;engine.Start();
|
||||
await Round();
|
||||
Check(engine.State==EngineState.Completed&&sop.Logs.Any(l=>l.Message.Contains("本轮结束图目录创建失败")),"归档目录创建失败有日志,检测继续完成");
|
||||
CheckRoundImages(second);
|
||||
Check(Directory.GetDirectories(archiveRoot).Length==2,"创建失败的轮次不会写入上一轮目录");
|
||||
}
|
||||
finally { sop.Recipes.Remove(blockedFile); }
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@ -94,6 +94,7 @@ internal static class Program
|
||||
steps:
|
||||
- id: 1
|
||||
description: 放好支架
|
||||
completion_image_directory: done
|
||||
must_keep: [支架]
|
||||
detection: { method: object_present, target_object: 支架 }
|
||||
""");
|
||||
@ -107,27 +108,25 @@ internal static class Program
|
||||
"散放旧配方只迁移标准视频,历史标注文件保留在原处");
|
||||
|
||||
var oldCompletion = Path.Combine(source.DirectoryFor(name), "done");
|
||||
config.Sop.Steps[0].CompletionImageDirectory = oldCompletion;
|
||||
SopConfigLoader.Save(config, source.ConfigPath(name));
|
||||
Directory.CreateDirectory(oldCompletion);
|
||||
File.WriteAllText(Path.Combine(oldCompletion, "historical.png"), "旧结束图");
|
||||
var archivedRecord = Path.Combine(source.DirectoryFor(name), "recipe-training.json");
|
||||
File.WriteAllText(archivedRecord, "历史文件按字节复制");
|
||||
target.ImportFrom(source.Root);
|
||||
target.Initialize();
|
||||
var imported = SopConfigLoader.Load(target.ConfigPath(name));
|
||||
Check(imported.Sop.Steps[0].CompletionImageDirectory == Path.Combine(target.DirectoryFor(name), "done") &&
|
||||
File.ReadAllBytes(Path.Combine(target.DirectoryFor(name), "recipe-training.json")).SequenceEqual(File.ReadAllBytes(archivedRecord)),
|
||||
"整目录导入时迁移完成图路径,历史文件按原样保留");
|
||||
Check(!File.ReadAllText(target.ConfigPath(name)).Contains("completion_image_directory") &&
|
||||
File.ReadAllBytes(Path.Combine(target.DirectoryFor(name), "recipe-training.json")).SequenceEqual(File.ReadAllBytes(archivedRecord)) &&
|
||||
File.Exists(Path.Combine(target.DirectoryFor(name), "done", "historical.png")),
|
||||
"整目录导入时清理旧结束图设置并保留已有图片和历史文件");
|
||||
}
|
||||
|
||||
/// <summary>导出→检查→导入的往返:内容一致、路径改写、不残留暂存目录。</summary>
|
||||
/// <summary>验证配方包往返保留步骤和保存开关,并清理临时文件。</summary>
|
||||
private static void RoundTrip()
|
||||
{
|
||||
var source = new RecipeWorkspace(Path.Combine(Root, "source"));
|
||||
var target = new RecipeWorkspace(Path.Combine(Root, "target"));
|
||||
const string name = "装配";
|
||||
var inside = Path.Combine(source.DirectoryFor(name), "done");
|
||||
var outside = Path.Combine(Root, "outside-images");
|
||||
Seed(source, name, inside, outside);
|
||||
Seed(source, name);
|
||||
|
||||
// 目标路径缺扩展名时补 .bwsrecipe,现场直接按扩展名识别配方包。
|
||||
var package = RecipePackage.Export(source, name, Path.Combine(Root, name)).Path;
|
||||
@ -140,7 +139,6 @@ internal static class Program
|
||||
var info = RecipePackage.Inspect(package);
|
||||
Check(info.RecipeName == name && info.FileCount == 3 && info.HasStandardVideo && info.TotalBytes > 0, "包摘要给出配方名、文件数、体积与标准视频");
|
||||
Check(info.ExportedAt is not null && !string.IsNullOrWhiteSpace(info.ApplicationVersion), "包记录导出时间和导出程序版本");
|
||||
Check(info.Warnings.Any(w => w.Contains("配方目录之外") && w.Contains("步骤 2")), "配方目录之外的完成图目录在导入前提醒并指出步骤");
|
||||
|
||||
var imported = RecipePackage.Import(target, package, name, false);
|
||||
Check(imported.Name == name && !imported.Overwrote && imported.ArchivedPath is null, "首次导入不声明覆盖也没有归档");
|
||||
@ -155,13 +153,12 @@ internal static class Program
|
||||
Check(migrated.Sop.Name == name && migrated.Sop.Steps.Count == 2 && migrated.Sop.Regions.ContainsKey("取料"), "导入保留步骤、区域和配方名");
|
||||
Check(migrated.Sop.Steps[0].Description.Contains("握住物料") && migrated.Sop.Steps[1].Detection!.Method == ConditionMethod.TimeElapsed,
|
||||
"步骤说明与判定方法逐字迁移,不经界面重写");
|
||||
Check(migrated.Sop.Steps[0].CompletionImageDirectory == "done", "配方目录内的完成图目录改写为相对路径");
|
||||
Check(migrated.Sop.Steps[1].CompletionImageDirectory.Length == 0, "配方目录之外的完成图目录被清空,不把工位本地路径带到新机器");
|
||||
Check(migrated.Sop.Steps[0].SaveCompletionImage && !migrated.Sop.Steps[1].SaveCompletionImage,
|
||||
"配方包保留各步骤的结束图保存开关");
|
||||
|
||||
var reimported = RecipePackage.Export(target, name, Path.Combine(Root, "re-export")).Path;
|
||||
var second = RecipePackage.Inspect(reimported);
|
||||
Check(second.FileCount == 3 && second.HasStandardVideo && !second.Warnings.Any(w => w.Contains("配方目录之外")),
|
||||
"导入后的配方可再次导出,完成图目录提醒不再重复出现");
|
||||
Check(second.FileCount == 3 && second.HasStandardVideo, "导入后的配方可再次导出");
|
||||
}
|
||||
|
||||
/// <summary>覆盖导入的归档行为、改名导入和改名建议。</summary>
|
||||
@ -170,7 +167,7 @@ internal static class Program
|
||||
var source = new RecipeWorkspace(Path.Combine(Root, "source2"));
|
||||
var target = new RecipeWorkspace(Path.Combine(Root, "target2"));
|
||||
const string name = "装配";
|
||||
Seed(source, name, Path.Combine(source.DirectoryFor(name), "done"), Path.Combine(Root, "outside2"));
|
||||
Seed(source, name);
|
||||
var package = RecipePackage.Export(source, name, Path.Combine(Root, "pack2")).Path;
|
||||
|
||||
var renamed = RecipePackage.Import(target, package, "装配二", false);
|
||||
@ -208,7 +205,7 @@ internal static class Program
|
||||
{
|
||||
var source = new RecipeWorkspace(Path.Combine(Root, "source3"));
|
||||
var target = new RecipeWorkspace(Path.Combine(Root, "target3"));
|
||||
Seed(source, "装配", Path.Combine(source.DirectoryFor("装配"), "done"), Path.Combine(Root, "outside3"));
|
||||
Seed(source, "装配");
|
||||
var package = RecipePackage.Export(source, "装配", Path.Combine(Root, "pack3")).Path;
|
||||
|
||||
var tampered = Tamper(package, keepLength: true);
|
||||
@ -260,8 +257,8 @@ internal static class Program
|
||||
Check(SopConfigLoader.Load(target.ConfigPath("无视频")).Sop.Steps.Single().Name == "计时", "导入后的步骤内容一致");
|
||||
}
|
||||
|
||||
/// <summary>写入用于导出的配方:配方目录内、目录外各一个完成图目录,并带标准 SOP 视频。</summary>
|
||||
private static void Seed(RecipeWorkspace workspace, string name, string insideDirectory, string outsideDirectory)
|
||||
/// <summary>写入带有标准视频及不同结束图开关状态的测试配方。</summary>
|
||||
private static void Seed(RecipeWorkspace workspace, string name)
|
||||
{
|
||||
Directory.CreateDirectory(workspace.DirectoryFor(name));
|
||||
var config = new SopConfig();
|
||||
@ -269,8 +266,8 @@ internal static class Program
|
||||
config.Sop.Regions["取料"] = new RegionDef { X1 = 10, Y1 = 20, X2 = 320, Y2 = 240, Name = "取料", Description = "料盒上方" };
|
||||
config.Sop.Steps =
|
||||
[
|
||||
new StepDef { Id = 1, Name = "取料", Description = "步骤说明:手在取料区握住物料", CompletionImageDirectory = insideDirectory, Detection = new StepCondition { Method = ConditionMethod.HandInRegion, Region = "取料" } },
|
||||
new StepDef { Id = 2, Name = "放置", Description = "步骤说明:物料放入放置区并保持稳定", CompletionImageDirectory = outsideDirectory, Detection = new StepCondition { Method = ConditionMethod.TimeElapsed, DurationMs = 2000 } }
|
||||
new StepDef { Id = 1, Name = "取料", Description = "步骤说明:手在取料区握住物料", Detection = new StepCondition { Method = ConditionMethod.HandInRegion, Region = "取料" } },
|
||||
new StepDef { Id = 2, Name = "放置", Description = "步骤说明:物料放入放置区并保持稳定", SaveCompletionImage = false, Detection = new StepCondition { Method = ConditionMethod.TimeElapsed, DurationMs = 2000 } }
|
||||
];
|
||||
SopConfigLoader.Save(config, workspace.ConfigPath(name));
|
||||
var stand = Path.Combine(workspace.DirectoryFor(name), "sop_stand");
|
||||
|
||||
@ -15,7 +15,7 @@ internal static class StepTransferChecks
|
||||
foreach (var key in new[] { "start", "finish", "inspect_area", "unused" })
|
||||
source.Sop.Regions[key] = new() { Name = key, X1 = 10, Y1 = 20, X2 = 100, Y2 = 120 };
|
||||
source.Sop.Steps = [new() { Id = 8, Name = "移动并确认", Description = "将零件移到终点", CompletionCriteria = "终点料盒内可见零件", Timeout = 17, StandardDurationMs = 3200,
|
||||
CompletionImageDirectory = "custom-images", SaveCompletionImage = false, RequiredObjects = ["零件"], MustKeep = ["工具"],
|
||||
SaveCompletionImage = false, RequiredObjects = ["零件"], MustKeep = ["工具"],
|
||||
ViolationRules = [new() { Type = "object_removed", Description = "工具移除", Severity = 3 }],
|
||||
Detection = new() { Method = "hand_move", FromRegion = "start", ToRegion = "finish", Hand = "left", StableFrames = 7, Tolerance = 9, MinConfidence = .81f },
|
||||
AiConfirmation = new() { EvidenceMode = "sequence", ImageMode = "fixed_region", ImageRegion = "inspect_area", CheckWindowMs = 32900,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user