239 lines
13 KiB
C#
239 lines
13 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using PLCSharp.VVMs.Vision;
|
|
using PLCSharp.VVMs.Vision.Camera;
|
|
using PLCSharp.VVMs.Homepage;
|
|
using PLCSharp.VVMs.GlobalVariables;
|
|
using System.Text.Json.Nodes;
|
|
|
|
namespace PLCSharp.Models;
|
|
|
|
public sealed record VisionStepEdit(Guid FunctionId, int Index, VisionFlowType Type, string Key,
|
|
bool HadValue, string Before, bool HasValue, string After)
|
|
{
|
|
internal VisionStepEdit Inverse() => new(FunctionId, Index, Type, Key, HasValue, After, HadValue, Before);
|
|
|
|
internal void Apply(JsonNode vision)
|
|
{
|
|
var function = vision["VisionFunctions"].AsArray().Single(f => Guid.Parse((string)f["ID"]) == FunctionId);
|
|
if (Index >= 0) ApplyToSteps(function["VisionFlows"]);
|
|
else if ((string)function[Key] == Before) function[Key] = After;
|
|
else throw new ProjectConflictException("视觉功能的显示控件已改变。");
|
|
}
|
|
|
|
internal void ApplyToSteps(JsonNode steps)
|
|
{
|
|
var step = steps[Index];
|
|
if ((int)step["Type"] != (int)Type || step["StringParams"] is not JsonObject args ||
|
|
args.ContainsKey(Key) != HadValue || (string)args[Key] != Before)
|
|
throw new ProjectConflictException("视觉步骤参数已改变,请重新预览。");
|
|
if (HasValue) args[Key] = After;
|
|
else args.Remove(Key);
|
|
}
|
|
}
|
|
|
|
public sealed partial class ProjectDirectory
|
|
{
|
|
private static Guid Owner(JsonNode row, string kind) => kind switch
|
|
{
|
|
"Cameras" => Guid.Empty,
|
|
"ImageDatas" or "CustomControls" or "SystemVariables" => Guid.Parse((string)row["RecipeID"]),
|
|
"LocalImageDatas" => Guid.Parse((string)row["FuncID"]),
|
|
_ => throw new ArgumentException("请选择 Cameras、ImageDatas 或 LocalImageDatas。")
|
|
};
|
|
|
|
private JsonNode CheckAssetName(string kind, Guid id, string before, string after)
|
|
{
|
|
if (kind is not ("Cameras" or "ImageDatas" or "LocalImageDatas" or "CustomControls" or "SystemVariables") || string.IsNullOrWhiteSpace(after) ||
|
|
after.Trim() != after || after == before) throw new ArgumentException("视觉对象类型或新名称无效。");
|
|
var rows = ProjectConfiguration.Capture(Data, [kind], false)[kind].AsArray();
|
|
var target = rows.Single(r => Guid.Parse((string)r["ID"]) == id);
|
|
if ((string)target["Name"] != before || rows.Any(r => r != target && Owner(r, kind) == Owner(target, kind) &&
|
|
((string)r["Name"] == after || (string)r["Name"] == before)))
|
|
throw new ProjectConflictException("对象已改变或在所属范围内存在重名。");
|
|
return target;
|
|
}
|
|
|
|
private static (string Key, string Fallback) Parameter(string kind, VisionFlowType type) => (kind, type) switch
|
|
{
|
|
("CustomControls", VisionFlowType.显示图像到主页) => ("CustomControlName", null),
|
|
("SystemVariables", VisionFlowType.坐标转换) => ("TransformMat", null),
|
|
("SystemVariables", VisionFlowType.距离) => ("Dist_TransMat", null),
|
|
("SystemVariables", VisionFlowType.卡尺寻边) => ("Caliper_TransformMat", null),
|
|
("SystemVariables", VisionFlowType.两线交点) => ("TwoLine_TransMat", null),
|
|
("SystemVariables", VisionFlowType.灰度模板匹配) => ("GrayMatch_TransMat", null),
|
|
("SystemVariables", VisionFlowType.ORB匹配) => ("Orb_TransMat", null),
|
|
("SystemVariables", VisionFlowType.SIFT匹配) => ("Sift_TransMat", null),
|
|
("SystemVariables", VisionFlowType.卡尺找圆) => ("CircleFind_TransMat", null),
|
|
("SystemVariables", VisionFlowType.卡尺找旋转矩形) => ("RectFind_TransMat", null),
|
|
("Cameras", VisionFlowType.拍照) => ("Camera", null),
|
|
("ImageDatas", VisionFlowType.从全局图像获取图片 or VisionFlowType.存到全局图像) => ("Image", null),
|
|
("LocalImageDatas", VisionFlowType.从局部图像获取图片 or VisionFlowType.存到局部图像 or VisionFlowType.图像相减) => ("Image", null),
|
|
("LocalImageDatas", VisionFlowType.ORB匹配) => ("TemplateName", "ORB_Template"),
|
|
("LocalImageDatas", VisionFlowType.灰度模板匹配) => ("TemplateName", "GrayMatch_Template"),
|
|
("LocalImageDatas", VisionFlowType.SIFT匹配) => ("TemplateName", "SIFT_Template"),
|
|
_ => default
|
|
};
|
|
|
|
internal ProjectRename PlanVisionAssetRename(string kind, Guid id, string after)
|
|
{
|
|
CheckSavedRecipes();
|
|
var target = ProjectInspection.Query(this, "get", new() { ["kind"] = kind, ["id"] = id.ToString() });
|
|
var before = (string)target["Name"];
|
|
CheckAssetName(kind, id, before, after);
|
|
var recipe = kind == "Cameras" ? Guid.Empty : Guid.Parse((string)target["RecipeID"]);
|
|
var vision = baseline[ConfigPath("vision")];
|
|
var plan = PlanReferences(kind, id, recipe, before, after);
|
|
List<VisionStepEdit> edits = [];
|
|
foreach (var func in JsonNode.Parse(vision)["VisionFunctions"].AsArray())
|
|
{
|
|
var fid = Guid.Parse((string)func["ID"]);
|
|
if (kind == "LocalImageDatas" && fid != Owner(target, kind) ||
|
|
recipe != Guid.Empty && recipe != Guid.Parse((string)func["RecipeID"])) continue;
|
|
if (!string.IsNullOrEmpty(before) && kind == "CustomControls" && (string)func["ControlName"] == before)
|
|
edits.Add(new(fid, -1, default, "ControlName", true, before, true, after));
|
|
var steps = func["VisionFlows"].AsArray();
|
|
for (int i = 0; i < steps.Count; i++)
|
|
{
|
|
var type = (VisionFlowType)(int)steps[i]["Type"];
|
|
var (key, fallback) = Parameter(kind, type);
|
|
if (key == null) continue;
|
|
var args = steps[i]["StringParams"].AsObject();
|
|
var value = (string)args[key];
|
|
if (kind == "SystemVariables" && type == VisionFlowType.坐标转换 && before == "标定矩阵" && string.IsNullOrEmpty(value))
|
|
plan.ManualReferences.Add(new JsonObject { ["confidence"] = "possible", ["path"] = ConfigPath("vision"),
|
|
["expression"] = $"{func["Name"]} / 步骤 {i + 1}:标定命令默认写入标定矩阵,运行步骤尚未选择矩阵。" });
|
|
if (!string.IsNullOrEmpty(before) && (string.IsNullOrEmpty(value) ? fallback : value) == before)
|
|
edits.Add(new(fid, i, type, key, args.ContainsKey(key), value, true, after));
|
|
}
|
|
}
|
|
return plan with { OriginalVision = vision, VisionReferences = edits };
|
|
}
|
|
|
|
private static Action PrepareSteps(ProjectRename plan, IEnumerable<VisionFunction> functions)
|
|
{
|
|
List<Action> actions = [];
|
|
foreach (var function in functions)
|
|
foreach (var edit in plan.VisionReferences.Where(e => e.FunctionId == function.ID))
|
|
{
|
|
if (edit.Index < 0)
|
|
{
|
|
if (function.ControlName != edit.Before) throw new ProjectConflictException("显示控件有未保存的编辑。");
|
|
actions.Add(() => function.ControlName = edit.After);
|
|
continue;
|
|
}
|
|
var step = function.VisionFlows.ElementAtOrDefault(edit.Index);
|
|
if (step?.Type != edit.Type || step.StringParams.TryGetValue(edit.Key, out var previous) != edit.HadValue ||
|
|
previous != edit.Before) throw new ProjectConflictException("视觉步骤存在未保存的修改。");
|
|
actions.Add(() =>
|
|
{
|
|
if (edit.HasValue) step.StringParams[edit.Key] = edit.After;
|
|
else step.StringParams.Remove(edit.Key);
|
|
});
|
|
}
|
|
return () => actions.ForEach(a => a());
|
|
}
|
|
|
|
internal Action PrepareAssetView(ProjectRename plan, VisionsModel model, Guid recipe,
|
|
IEnumerable<CustomControl> controls, IEnumerable<SystemVariable> systemVariables)
|
|
{
|
|
if (plan.Kind != "Cameras" && recipe != plan.RecipeId) return null;
|
|
IEnumerable<INamedDevice> objects = plan.Kind switch
|
|
{
|
|
"SystemVariables" => systemVariables,
|
|
"CustomControls" => controls,
|
|
"Cameras" => model.Cameras,
|
|
"ImageDatas" => model.ImageDatas,
|
|
_ => model.VisionFunctions.Single(f => f.ID == Data.LocalImageDatas.Find(plan.ObjectId).FuncID).LocalImageDatas
|
|
};
|
|
var target = objects.Single(o => o.ID == plan.ObjectId);
|
|
if (target.Name != plan.OldName || objects.Any(o => o.ID != target.ID && (o.Name == plan.NewName || o.Name == plan.OldName)))
|
|
throw new ProjectConflictException("编辑器中的名称已改变。");
|
|
var steps = PrepareSteps(plan, model.VisionFunctions);
|
|
return () =>
|
|
{
|
|
target.SetReviewedName(plan.NewName);
|
|
if (target is CameraBase cam) cam.Params.DiscoveryName = Data.Cameras.Find(target.ID).Params.DiscoveryName;
|
|
steps();
|
|
};
|
|
}
|
|
|
|
private Action WriteVisionAsset(ProjectRename plan, Dictionary<string, string> files)
|
|
{
|
|
INamedDevice target = plan.Kind switch
|
|
{
|
|
"SystemVariables" => Data.SystemVariables.Find(plan.ObjectId),
|
|
"CustomControls" => Data.CustomControls.Find(plan.ObjectId),
|
|
"Cameras" => Data.Cameras.Find(plan.ObjectId),
|
|
"ImageDatas" => Data.ImageDatas.Find(plan.ObjectId),
|
|
_ => Data.LocalImageDatas.Find(plan.ObjectId)
|
|
};
|
|
if (target.Name != plan.OldName) throw new ProjectConflictException("对象存在未保存的名称修改。");
|
|
var id = plan.ObjectId;
|
|
string discovery = null;
|
|
int count;
|
|
if (target is CameraBase)
|
|
{
|
|
var row = JsonNode.Parse(files[plan.MetadataPath])["Cameras"].AsArray().Single(r => Guid.Parse((string)r["ID"]) == id);
|
|
discovery = (string)row["Params"]?["DiscoveryName"];
|
|
var json = row["Params"].ToJsonString();
|
|
count = Data.Cameras.Where(c => c.ID == id && c.Name == plan.OldName)
|
|
.ExecuteUpdate(s => s.SetProperty(c => c.Name, plan.NewName).SetProperty(c => c.SerializedParams, json));
|
|
}
|
|
else if (target is SystemVariable)
|
|
count = Data.SystemVariables.Where(i => i.ID == id && i.Name == plan.OldName).ExecuteUpdate(s => s.SetProperty(i => i.Name, plan.NewName));
|
|
else if (target is CustomControl)
|
|
count = Data.CustomControls.Where(i => i.ID == id && i.Name == plan.OldName).ExecuteUpdate(s => s.SetProperty(i => i.Name, plan.NewName));
|
|
else if (target is ImageData)
|
|
count = Data.ImageDatas.Where(i => i.ID == id && i.Name == plan.OldName).ExecuteUpdate(s => s.SetProperty(i => i.Name, plan.NewName));
|
|
else
|
|
count = Data.LocalImageDatas.Where(i => i.ID == id && i.Name == plan.OldName).ExecuteUpdate(s => s.SetProperty(i => i.Name, plan.NewName));
|
|
if (count != 1) throw new ProjectConflictException("视觉对象已改变。");
|
|
var acceptSteps = WriteVisionSteps(plan);
|
|
return () =>
|
|
{
|
|
target.SetReviewedName(plan.NewName);
|
|
Data.Entry((object)target).Property("Name").OriginalValue = plan.NewName;
|
|
if (target is CameraBase camera)
|
|
{
|
|
camera.Params.DiscoveryName = discovery;
|
|
Data.Entry(camera).Property(c => c.SerializedParams).OriginalValue = camera.SerializedParams;
|
|
}
|
|
acceptSteps();
|
|
};
|
|
}
|
|
|
|
private Action WriteVisionSteps(ProjectRename plan)
|
|
{
|
|
List<VisionFunction> tracked = [];
|
|
foreach (var group in plan.VisionReferences.GroupBy(e => e.FunctionId))
|
|
{
|
|
var fid = group.Key;
|
|
tracked.Add(Data.VisionFunctions.Find(fid));
|
|
foreach (var binding in group.Where(e => e.Index < 0))
|
|
if (Data.VisionFunctions.Where(f => f.ID == fid && f.ControlName == binding.Before)
|
|
.ExecuteUpdate(s => s.SetProperty(f => f.ControlName, binding.After)) != 1)
|
|
throw new ProjectConflictException("视觉功能的控件绑定已改变。");
|
|
if (group.All(e => e.Index < 0)) continue;
|
|
var raw = Data.VisionFunctions.Where(f => f.ID == fid).Select(f => f.SerializedVisionFlows).Single();
|
|
var steps = JsonNode.Parse(raw);
|
|
foreach (var edit in group.Where(e => e.Index >= 0)) edit.ApplyToSteps(steps);
|
|
var json = steps.ToJsonString();
|
|
if (Data.VisionFunctions.Where(f => f.ID == fid && f.SerializedVisionFlows == raw)
|
|
.ExecuteUpdate(s => s.SetProperty(f => f.SerializedVisionFlows, json)) != 1)
|
|
throw new ProjectConflictException("视觉步骤已经改变。");
|
|
}
|
|
var update = PrepareSteps(plan, tracked);
|
|
return () =>
|
|
{
|
|
update();
|
|
foreach (var f in tracked)
|
|
{
|
|
if (plan.VisionReferences.Any(e => e.FunctionId == f.ID && e.Index >= 0))
|
|
Data.Entry(f).Property(v => v.SerializedVisionFlows).OriginalValue = f.SerializedVisionFlows;
|
|
if (plan.VisionReferences.Any(e => e.FunctionId == f.ID && e.Index < 0))
|
|
Data.Entry(f).Property(v => v.ControlName).OriginalValue = f.ControlName;
|
|
}
|
|
};
|
|
}
|
|
}
|