164 lines
7.5 KiB
C#
164 lines
7.5 KiB
C#
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using YamlDotNet.Serialization;
|
||
using YamlDotNet.Serialization.NamingConventions;
|
||
|
||
namespace SopHelper.Engine.Sop;
|
||
|
||
/// <summary>
|
||
/// 配方加载器:YAML → SopConfig,并做可用性校验(校验结果进 Warnings,界面要显示)。
|
||
/// 反向的 ToYaml/Save 给配方编辑器用。
|
||
/// </summary>
|
||
public static partial class SopConfigLoader
|
||
{
|
||
/// <summary>
|
||
/// 读一个配方文件
|
||
/// </summary>
|
||
public static SopConfig Load(string yamlPath)
|
||
{
|
||
var config = Parse(File.ReadAllText(yamlPath));
|
||
|
||
if (string.IsNullOrWhiteSpace(config.Sop.Name))
|
||
config.Warnings.Add("配方缺少 sop.name");
|
||
|
||
return config;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 从 YAML 文本解析(与 Load 同一套校验,便于单测)
|
||
/// </summary>
|
||
public static SopConfig Parse(string yaml)
|
||
{
|
||
var deserializer = new DeserializerBuilder()
|
||
.WithNamingConvention(UnderscoredNamingConvention.Instance)
|
||
.WithCaseInsensitivePropertyMatching()
|
||
.IgnoreUnmatchedProperties()
|
||
.Build();
|
||
|
||
var config = deserializer.Deserialize<SopConfig>(yaml) ?? new SopConfig();
|
||
|
||
Validate(config);
|
||
|
||
return config;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 把配方写回 YAML 文本(编辑器保存用)。注释会丢——YamlDotNet 不保留注释,
|
||
/// 所以 demo.yaml 里那些说明性注释只在手写的原始文件里有。
|
||
/// </summary>
|
||
public static string ToYaml(SopConfig config)
|
||
{
|
||
var serializer = new SerializerBuilder()
|
||
.WithNamingConvention(UnderscoredNamingConvention.Instance)
|
||
.WithNewLine("\n")
|
||
.WithQuotingNecessaryStrings()
|
||
.Build();
|
||
|
||
var yaml = serializer.Serialize(config);
|
||
|
||
// 没配模型时别留一个空的 model: 节点——它会被读成"有 model 但 path 为空",
|
||
// 校验里那几条"需要模型"的提醒就哑了(本可空手告诉你的手已经空了)。
|
||
if (config.Sop.Model is null)
|
||
yaml = string.Join("\n", yaml.Split('\n').Where(l => l.TrimEnd() != " model:"));
|
||
|
||
return yaml.TrimEnd('\n') + "\n";
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写回文件,并顺手校验一遍(校验提醒随返回值给出,编辑器要显示)。
|
||
/// </summary>
|
||
public static SopConfig Save(SopConfig config, string yamlPath)
|
||
{
|
||
File.WriteAllText(yamlPath, ToYaml(config), new UTF8Encoding(false));
|
||
|
||
// 落盘后再读一遍:校验的是文件里真正的内容,不是内存里那份
|
||
return Load(yamlPath);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 校验:配方里写了引擎没实现的方法,一定要在这里报出来,
|
||
/// 否则现场表现是"这一步永远不推进",极难定位。
|
||
/// </summary>
|
||
public static void Validate(SopConfig config)
|
||
{
|
||
config.Sop.Model = null; // 旧配方模型字段不再参与运行。
|
||
var supported = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||
{
|
||
ConditionMethod.HandInRegion,
|
||
ConditionMethod.HandLeaveRegion,
|
||
ConditionMethod.HandMove,
|
||
ConditionMethod.TimeElapsed,
|
||
};
|
||
|
||
var regionNames = new HashSet<String>(config.Sop.Regions.Keys, StringComparer.OrdinalIgnoreCase);
|
||
|
||
if (config.Sop.Steps.Count == 0)
|
||
config.Warnings.Add("配方没有任何步骤");
|
||
|
||
// 起始步骤取最小 Id(配方步骤不固定从 1 开始)
|
||
var ordered = config.Sop.Steps.OrderBy(s => s.Id).ToList();
|
||
if (ordered.Count > 0 && ordered[0].Id != config.Sop.Steps.Min(s => s.Id))
|
||
config.Warnings.Add("步骤顺序与 Id 不一致,执行顺序按 Id 升序");
|
||
|
||
foreach (var step in ordered)
|
||
{
|
||
step.AiConfirmation ??= new AiConfirmation();
|
||
if (step.AiConfirmation is { } ai)
|
||
{
|
||
if (!ConditionMethod.SupportsAiTrigger(step.Detection?.Method))
|
||
config.Warnings.Add($"步骤 {step.Id} 的 AI 确认必须使用手进入区域、离开区域或区域间移动触发");
|
||
if (!VisionImageMode.IsValid(ai)) config.Warnings.Add($"步骤 {step.Id} 的 AI 取图方式或手部范围参数无效");
|
||
if (!VisionEvidenceMode.IsValid(ai)) config.Warnings.Add($"步骤 {step.Id} 的过程证据模式或观察窗口参数无效");
|
||
if (VisionImageMode.Resolve(ai) == VisionImageMode.FixedRegion)
|
||
{
|
||
var region = config.Sop.Regions.FirstOrDefault(p => p.Key.Equals(ai.ImageRegion, StringComparison.OrdinalIgnoreCase)).Value;
|
||
if (region is null || region.X1 < 0 || region.Y1 < 0 || region.X2 <= region.X1 || region.Y2 <= region.Y1)
|
||
config.Warnings.Add($"步骤 {step.Id} 的 AI 取图区域 '{ai.ImageRegion}' 不存在或坐标无效");
|
||
}
|
||
if (string.IsNullOrWhiteSpace(step.Description))
|
||
config.Warnings.Add($"步骤 {step.Id}({step.Name})请填写步骤说明,AI 按说明确认,填写前不会自动推进");
|
||
if (!double.IsFinite(ai.MinConfidence) || ai.MinConfidence is < 0 or > 1
|
||
|| ai.RetryDelayMs < 0 || ai.TimeoutSeconds <= 0)
|
||
config.Warnings.Add($"步骤 {step.Id} 的 AI 判据、置信度、重试间隔或超时配置无效");
|
||
if (step.MustKeep.Count > 0 || step.RequiredObjects.Count > 0)
|
||
config.Warnings.Add($"步骤 {step.Id} 使用 AI 确认时,请将物料要求写入 AI 完成判据,物体规则已移除");
|
||
}
|
||
var condition = step.Detection;
|
||
if (condition is null)
|
||
{
|
||
config.Warnings.Add($"步骤 {step.Id}({step.Name})未设置完成条件,请选择判定方法;等待后完成请选择 time_elapsed");
|
||
continue;
|
||
}
|
||
if (condition.Method is ConditionMethod.HandInRegion or ConditionMethod.HandLeaveRegion && string.IsNullOrWhiteSpace(condition.Region))
|
||
config.Warnings.Add($"步骤 {step.Id}({step.Name})请设置触发区域");
|
||
if (condition.Method == ConditionMethod.HandMove && (string.IsNullOrWhiteSpace(condition.FromRegion) || string.IsNullOrWhiteSpace(condition.ToRegion)))
|
||
config.Warnings.Add($"步骤 {step.Id}({step.Name})请设置起点和终点区域");
|
||
|
||
if (!supported.Contains(condition.Method))
|
||
{
|
||
config.Warnings.Add(
|
||
$"步骤 {step.Id} 的方法 '{condition.Method}' 已移除或不支持(请改用:{string.Join(", ", supported)}),该条件视为不满足");
|
||
}
|
||
|
||
// 区域引用检查(区域没标定 → 现场就是不推进)
|
||
foreach (var name in new[] { condition.Region, condition.FromRegion, condition.ToRegion })
|
||
{
|
||
if (string.IsNullOrWhiteSpace(name)) continue;
|
||
|
||
if (!regionNames.Contains(name))
|
||
config.Warnings.Add($"步骤 {step.Id} 引用了未定义的区域 '{name}'");
|
||
}
|
||
|
||
foreach (var rule in step.ViolationRules)
|
||
{
|
||
if (rule.Type.Equals(ViolationType.Timeout, StringComparison.OrdinalIgnoreCase)
|
||
&& step.Timeout <= 0)
|
||
{
|
||
config.Warnings.Add($"步骤 {step.Id} 配了超时违规但 timeout=0,不会触发");
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
}
|