Apply and undo reviewed device names and workflow edits in the live editor

This commit is contained in:
wanglei 2026-12-05 22:25:25 +08:00
parent dc5463b3bb
commit fc49db64a8
13 changed files with 161 additions and 15 deletions

View File

@ -28,7 +28,7 @@ internal sealed class ProjectGateway(string root, bool allowWrite)
return ProjectPipe.Call(root, new() { ["operation"] = operation, ["arguments"] = arguments }, () => return ProjectPipe.Call(root, new() { ["operation"] = operation, ["arguments"] = arguments }, () =>
{ {
using var project = ProjectDirectory.Open(root); using var project = ProjectDirectory.Open(root);
if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewUndo" or "apply" or "status") if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status")
return changes.Execute(project, operation, arguments, allowWrite, change => (change.Review == null && change.Rename == null) || approved); return changes.Execute(project, operation, arguments, allowWrite, change => (change.Review == null && change.Rename == null) || approved);
return ProjectInspection.Query(project, operation, arguments); return ProjectInspection.Query(project, operation, arguments);
}).ToJsonString(); }).ToJsonString();

View File

@ -11,6 +11,10 @@ internal sealed class ProjectTools(ProjectGateway gateway)
public string PreviewVisionFunctionRename(string id, string newName) => public string PreviewVisionFunctionRename(string id, string newName) =>
gateway.Call("previewVisionRename", new() { ["id"] = id, ["newName"] = newName }); gateway.Call("previewVisionRename", new() { ["id"] = id, ["newName"] = newName });
[McpServerTool(Name = "preview_device_rename"), Description("Preview renaming a Cylinders, Robots or Connects ID. Updates the hardware definition and bound lookups across recipes, compiles affected scripts and lists manual references.")]
public string PreviewDeviceRename(string kind, string id, string newName) =>
gateway.Call("previewDeviceRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName });
[McpServerTool(Name = "preview_io_rename"), Description("Preview renaming a DI or DQ channel across the project, including cylinder bindings and compiled workflow references.")] [McpServerTool(Name = "preview_io_rename"), Description("Preview renaming a DI or DQ channel across the project, including cylinder bindings and compiled workflow references.")]
public string PreviewIoRename(string kind, string id, string newName) => public string PreviewIoRename(string kind, string id, string newName) =>
gateway.Call("previewIoRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName }); gateway.Call("previewIoRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName });

View File

@ -0,0 +1,50 @@
using PLCSharp.VVMs.Connects;
using PLCSharp.VVMs.Robots;
using System.Text.Json.Nodes;
namespace PLCSharp.Models;
internal interface INamedDevice
{
Guid ID { get; }
string Name { get; }
void SetReviewedName(string value);
}
public sealed partial class ProjectDirectory
{
internal ProjectRename PlanDeviceRename(string kind, Guid id, string newName)
{
if (kind is not ("Cylinders" or "Robots" or "Connects"))
throw new ArgumentException("请选择 Cylinders、Robots 或 Connects。");
CheckSavedRecipes();
var hardware = JsonNode.Parse(baseline[ConfigPath("hardware")]);
var oldName = (string)new PointField(kind, id, "Name").Row(hardware)["Name"];
CheckHardwareName(kind, id, oldName, newName, false);
return PlanReferences(kind, id, Guid.Empty, oldName, newName);
}
}
public partial class GlobalModel
{
private Action PrepareDeviceView(ProjectRename plan)
{
IEnumerable<INamedDevice> devices = plan.Kind switch
{
"Cylinders" => CylindersModel.Cylinders,
"Robots" => RobotModel.Robots,
"Connects" => Connects.Connects,
_ => throw new ArgumentException("未知设备类型。")
};
var target = devices.SingleOrDefault(d => d.ID == plan.ObjectId);
if (devices.Any(d => d.ID != plan.ObjectId && !string.IsNullOrEmpty(d.Name) &&
(d.Name == plan.OldName || d.Name == plan.NewName)))
throw new ProjectConflictException("编辑器中存在同名设备。");
// Undefined devices are saved definitions without a live driver instance.
if (target == null && (plan.Kind == "Robots" && Project.Data.Robots.Find(plan.ObjectId)?.Type == RobotType.Undefined ||
plan.Kind == "Connects" && Project.Data.Connects.Find(plan.ObjectId)?.Type == ProtocolType.Undefined)) return null;
if (target == null || target.Name != plan.OldName)
throw new ProjectConflictException("编辑器设备列表已改变,请先保存并重新预览。");
return () => target.SetReviewedName(plan.NewName);
}
}

View File

@ -32,7 +32,7 @@ public partial class GlobalModel
if (!AllowAiAccess) throw new InvalidOperationException("请在机种配方页面启用 AI 访问。"); if (!AllowAiAccess) throw new InvalidOperationException("请在机种配方页面启用 AI 访问。");
string operation = (string)request["operation"]; string operation = (string)request["operation"];
var args = request["arguments"].AsObject(); var args = request["arguments"].AsObject();
if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewUndo" or "apply" or "status") if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status")
{ {
if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy)) if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy))
throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。");
@ -74,6 +74,8 @@ public partial class GlobalModel
updateEditorView = Project.PrepareAxisView(axis, ControllersModel, CurrentRecipe.ID); updateEditorView = Project.PrepareAxisView(axis, ControllersModel, CurrentRecipe.ID);
if (accepted && change.Rename is { IsIo: true } io) if (accepted && change.Rename is { IsIo: true } io)
updateEditorView = Project.PrepareIoView(io, ControllersModel, CylindersModel); updateEditorView = Project.PrepareIoView(io, ControllersModel, CylindersModel);
if (accepted && change.Rename is { IsDevice: true } device)
updateEditorView = PrepareDeviceView(device);
return accepted; return accepted;
}); });
if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke(); if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke();

View File

@ -12,14 +12,22 @@ public sealed partial class ProjectDirectory
_ => throw new ArgumentException("请选择 DI 或 DQ。") _ => throw new ArgumentException("请选择 DI 或 DQ。")
}; };
private void CheckIoName(string kind, Guid id, string before, string after, bool inverse) private void CheckHardwareName(string kind, Guid id, string before, string after, bool inverse)
{ {
if ((!inverse && string.IsNullOrWhiteSpace(after)) || after != after?.Trim() || before == after) if ((!inverse && string.IsNullOrWhiteSpace(after)) || after != after?.Trim() || before == after)
throw new ArgumentException("请输入不同的新名称,首尾不能有空白。"); throw new ArgumentException("请输入不同的新名称,首尾不能有空白。");
var rows = kind == "DI" ? Data.DI.Select(p => new { p.ID, p.Name }) : Data.DQ.Select(p => new { p.ID, p.Name }); var rows = kind switch
{
"DI" => Data.DI.Select(p => new { p.ID, p.Name }),
"DQ" => Data.DQ.Select(p => new { p.ID, p.Name }),
"Robots" => Data.Robots.Select(p => new { p.ID, p.Name }),
"Cylinders" => Data.Cylinders.Select(p => new { p.ID, p.Name }),
"Connects" => Data.Connects.Select(p => new { p.ID, p.Name }),
_ => throw new ArgumentException("未知硬件类型。")
};
if (!rows.Any(p => p.ID == id && p.Name == before) || rows.Any(p => p.ID != id && if (!rows.Any(p => p.ID == id && p.Name == before) || rows.Any(p => p.ID != id &&
((before != null && before != "" && p.Name == before) || (after != null && after != "" && p.Name == after)))) ((before != null && before != "" && p.Name == before) || (after != null && after != "" && p.Name == after))))
throw new ProjectConflictException("通道已更改或同类通道存在重名。"); throw new ProjectConflictException("设备已更改或同类设备存在重名。");
} }
internal ProjectRename PlanIoRename(string kind, Guid id, string newName) internal ProjectRename PlanIoRename(string kind, Guid id, string newName)
@ -28,7 +36,7 @@ public sealed partial class ProjectDirectory
CheckSavedRecipes(); CheckSavedRecipes();
var hardware = JsonNode.Parse(baseline[ConfigPath("hardware")]); var hardware = JsonNode.Parse(baseline[ConfigPath("hardware")]);
var old = (string)new PointField(kind, id, "Name").Row(hardware)["Name"]; var old = (string)new PointField(kind, id, "Name").Row(hardware)["Name"];
CheckIoName(kind, id, old, newName, false); CheckHardwareName(kind, id, old, newName, false);
var links = new List<PointField>(); var links = new List<PointField>();
foreach (var row in hardware["Cylinders"].AsArray()) foreach (var row in hardware["Cylinders"].AsArray())
foreach (var field in fields) foreach (var field in fields)

View File

@ -12,6 +12,7 @@ public sealed record PointField(string Table, Guid Id, string Field)
internal Type EntityType => Table switch internal Type EntityType => Table switch
{ {
"DI" => typeof(DI), "DQ" => typeof(DQ), "Cylinders" => typeof(PLCSharp.VVMs.Cylinders.Cylinder), "DI" => typeof(DI), "DQ" => typeof(DQ), "Cylinders" => typeof(PLCSharp.VVMs.Cylinders.Cylinder),
"Robots" => typeof(Robot), "Connects" => typeof(PLCSharp.VVMs.Connects.Connect),
"Axes" => typeof(Axis), "InterpolationGroups" => typeof(InterpolationGroup), "Axes" => typeof(Axis), "InterpolationGroups" => typeof(InterpolationGroup),
"AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint),
"Matrices" => typeof(Matrix), "RobotMatrices" => typeof(RobotMatrix), "Matrices" => typeof(Matrix), "RobotMatrices" => typeof(RobotMatrix),

View File

@ -26,10 +26,12 @@ public sealed class ProjectChanges
public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite,
Func<ProjectChange, bool> confirm = null) Func<ProjectChange, bool> confirm = null)
{ {
if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewUndo") if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewDeviceRename" or "previewUndo")
{ {
ProjectRename plan; ProjectRename plan;
if (operation == "previewIoRename") if (operation == "previewDeviceRename")
plan = project.PlanDeviceRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]);
else if (operation == "previewIoRename")
plan = project.PlanIoRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]); plan = project.PlanIoRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]);
else if (operation == "previewAxisRename") else if (operation == "previewAxisRename")
plan = project.PlanAxisRename(Guid.Parse((string)args["id"]), (string)args["newName"]); plan = project.PlanAxisRename(Guid.Parse((string)args["id"]), (string)args["newName"]);

View File

@ -22,11 +22,12 @@ public sealed record ProjectRename(Guid ObjectId, Guid RecipeId, string OldName,
{ {
"AxisPoints" or "RobotPoints" => "configuration/points.json", "AxisPoints" or "RobotPoints" => "configuration/points.json",
"VisionFunctions" => "configuration/vision.json", "VisionFunctions" => "configuration/vision.json",
"DI" or "DQ" or "Axes" => "configuration/hardware.json", "DI" or "DQ" or "Axes" or "Cylinders" or "Robots" or "Connects" => "configuration/hardware.json",
"Workflows" => $"recipes/{recipe:D}/recipe.json", "Workflows" => $"recipes/{recipe:D}/recipe.json",
_ => ProjectDirectory.VariablesPath _ => ProjectDirectory.VariablesPath
}; };
public List<PointField> MatrixReferences { get; init; } = []; public List<PointField> MatrixReferences { get; init; } = [];
public bool IsDevice => Kind is "Cylinders" or "Robots" or "Connects";
public bool IsIo => Kind is "DI" or "DQ"; public bool IsIo => Kind is "DI" or "DQ";
public List<PointField> CylinderReferences { get; init; } = []; public List<PointField> CylinderReferences { get; init; } = [];
public List<PointField> PointReferences { get; init; } = []; public List<PointField> PointReferences { get; init; } = [];
@ -142,7 +143,7 @@ public sealed partial class ProjectDirectory
{ {
if (plan.Kind == "Workflows") CheckWorkflowName(plan.RecipeId, plan.ObjectId, before, after); if (plan.Kind == "Workflows") CheckWorkflowName(plan.RecipeId, plan.ObjectId, before, after);
else if (plan.Kind == "VisionFunctions") CheckVisionName(plan.RecipeId, plan.ObjectId, before, after); else if (plan.Kind == "VisionFunctions") CheckVisionName(plan.RecipeId, plan.ObjectId, before, after);
else if (plan.IsIo) CheckIoName(plan.Kind, plan.ObjectId, before, after, plan.UndoOf.HasValue || plan.SavedMetadata != null); else if (plan.IsIo || plan.IsDevice) CheckHardwareName(plan.Kind, plan.ObjectId, before, after, plan.UndoOf.HasValue || plan.SavedMetadata != null);
else if (plan.Kind == "Axes") CheckAxisName(plan.ObjectId, before, after); else if (plan.Kind == "Axes") CheckAxisName(plan.ObjectId, before, after);
else if (plan.IsPoint) ValidatePoint(plan, before, after); else if (plan.IsPoint) ValidatePoint(plan, before, after);
else CheckVariableName(plan.RecipeId, plan.ObjectId, before, after); else CheckVariableName(plan.RecipeId, plan.ObjectId, before, after);
@ -212,7 +213,7 @@ public sealed partial class ProjectDirectory
if (plan.Kind == "VisionFunctions" && Data.VisionFunctions.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName) if (plan.Kind == "VisionFunctions" && Data.VisionFunctions.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName)
.ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1) .ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1)
throw new ProjectConflictException("视觉功能已发生变化。"); throw new ProjectConflictException("视觉功能已发生变化。");
if (plan.IsPoint || plan.IsIo || plan.Kind == "Axes") WritePointFields(plan); if (plan.IsPoint || plan.IsIo || plan.IsDevice || plan.Kind == "Axes") WritePointFields(plan);
if (plan.Kind == "Variables" && Data.Variables.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName) if (plan.Kind == "Variables" && Data.Variables.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName)
.ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1) .ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1)
throw new ProjectConflictException("变量已发生变化。"); throw new ProjectConflictException("变量已发生变化。");
@ -230,6 +231,13 @@ public sealed partial class ProjectDirectory
configuration[plan.MetadataPath] = files[plan.MetadataPath]; configuration[plan.MetadataPath] = files[plan.MetadataPath];
if (plan.Kind == "Axes") if (plan.Kind == "Axes")
configuration[ConfigPath("points")] = files[ConfigPath("points")]; configuration[ConfigPath("points")] = files[ConfigPath("points")];
if (plan.IsDevice)
{
var device = (INamedDevice)Data.Find(new PointField(plan.Kind, plan.ObjectId, "Name").EntityType, plan.ObjectId);
device.SetReviewedName(plan.NewName);
Data.Entry((object)device).Property("Name").OriginalValue = plan.NewName;
return;
}
if (plan.IsPoint || plan.IsIo || plan.Kind == "Axes") if (plan.IsPoint || plan.IsIo || plan.Kind == "Axes")
{ {
AcceptPointFields(plan); AcceptPointFields(plan);

View File

@ -25,7 +25,7 @@ namespace PLCSharp.VVMs.Connects
/// <summary> /// <summary>
/// 连接 /// 连接
/// </summary> /// </summary>
public class Connect : BindableBase public class Connect : BindableBase, PLCSharp.Models.INamedDevice
{ {
/// <summary> /// <summary>
/// 唯一标识 /// 唯一标识
@ -42,6 +42,8 @@ namespace PLCSharp.VVMs.Connects
private string _Name; private string _Name;
void PLCSharp.Models.INamedDevice.SetReviewedName(string value) => SetProperty(ref _Name, value, nameof(Name));
/// <summary> /// <summary>
/// 连接配置 /// 连接配置
/// </summary> /// </summary>

View File

@ -20,7 +20,7 @@ namespace PLCSharp.VVMs.Cylinders
/// <summary> /// <summary>
/// 气缸 /// 气缸
/// </summary> /// </summary>
public class Cylinder : BindableBase public class Cylinder : BindableBase, PLCSharp.Models.INamedDevice
{ {
/// <summary> /// <summary>
/// 唯一标识 /// 唯一标识
@ -30,6 +30,8 @@ namespace PLCSharp.VVMs.Cylinders
private string _Name; private string _Name;
void PLCSharp.Models.INamedDevice.SetReviewedName(string value) => SetProperty(ref _Name, value, nameof(Name));
/// <summary> /// <summary>
/// 气缸名称 /// 气缸名称
/// </summary> /// </summary>

View File

@ -13,7 +13,7 @@ namespace PLCSharp.VVMs.Robots
/// <summary> /// <summary>
/// 机器人 /// 机器人
/// </summary> /// </summary>
public class Robot : BindableBase public class Robot : BindableBase, PLCSharp.Models.INamedDevice
{ {
[NotMapped] [NotMapped]
public RobotModel Model { get; set; } public RobotModel Model { get; set; }
@ -26,6 +26,8 @@ namespace PLCSharp.VVMs.Robots
private string _Name; private string _Name;
void PLCSharp.Models.INamedDevice.SetReviewedName(string value) => SetProperty(ref _Name, value, nameof(Name));
/// <summary> /// <summary>
/// 机器人名称 /// 机器人名称
/// </summary> /// </summary>

View File

@ -11,7 +11,8 @@ public partial class ScriptReviewWindow : Window
InitializeComponent(); InitializeComponent();
if (change.Rename is { } rename) if (change.Rename is { } rename)
{ {
var subject = rename.Kind switch { "DI" => "数字输入", "DQ" => "数字输出", "Axes" => "运动轴", "VisionFunctions" => "视觉功能", "Workflows" => "工作流", var subject = rename.Kind switch { "Cylinders" => "气缸", "Robots" => "机器人", "Connects" => "通信连接",
"DI" => "数字输入", "DQ" => "数字输出", "Axes" => "运动轴", "VisionFunctions" => "视觉功能", "Workflows" => "工作流",
"AxisPoints" or "RobotPoints" => "点位", _ => "变量" }; "AxisPoints" or "RobotPoints" => "点位", _ => "变量" };
Title = $"确认{(rename.UndoOf.HasValue ? "撤销" : "")}{subject}重命名"; Title = $"确认{(rename.UndoOf.HasValue ? "撤销" : "")}{subject}重命名";
WorkflowTitle.Text = $"{rename.OldName} → {rename.NewName}"; WorkflowTitle.Text = $"{rename.OldName} → {rename.NewName}";

View File

@ -0,0 +1,64 @@
using PLCSharp.Models;
using PLCSharp.VVMs.Connects;
using PLCSharp.VVMs.Cylinders;
using PLCSharp.VVMs.Robots;
using PLCSharp.VVMs.Workflows;
using System.IO;
namespace PLCSharp.Tests;
public class DeviceRenameTests
{
[Fact]
public void SameNamedHardwareIsScopedByTypeAndNamedParametersBindToTheConnection()
{
var root = Directory.CreateTempSubdirectory();
try
{
using var p = ProjectDirectory.New();
var cylinder = new Cylinder { Name = "Common", InA = "Common" };
var robot = new Robot { Name = "Common" };
var connect = new Connect { Name = "Common" };
p.Data.AddRange(cylinder, robot, connect, new Robot { Name = "Existing" });
var flow = new Workflow { RecipeID = p.DefaultRecipeId, Name = "Inspect" };
flow.Code = $$"""
using System.Linq;
using PLCSharp.Models;
using PLCSharp.Core.Common;
public class Extension_{{flow.ID:N}} {
public void Run(GlobalModel model, FlowModel flow) {
const string label = "Common";
_ = model.CylindersModel.Cylinders.FirstOrDefault(c => c.Name == label);
_ = model.GetRobot(label);
_ = model.RobotModel.Robots.FirstOrDefault(r => r.Name == label);
_ = model.GetConnect(label);
model.Connects.ApplyDataItemToServer(item: null, connectName: label);
_ = model.Connects.Connects.FirstOrDefault(c => c.Name == flow.Step.ToString());
}
}
""";
p.Flows(flow.RecipeID).Add(flow);
p.Save(root.FullName);
var before = File.ReadAllBytes(Path.Combine(root.FullName, "configuration", "hardware.json"));
Assert.ThrowsAny<IOException>(() => p.PlanDeviceRename("Robots", robot.ID, "Existing"));
var plans = new Stack<ProjectRename>();
foreach (var (kind, id) in new[] { ("Cylinders", cylinder.ID), ("Robots", robot.ID), ("Connects", connect.ID) })
{
var plan = p.PlanDeviceRename(kind, id, kind);
Assert.True(plan.Compiled);
p.ApplyRename(plan);
plans.Push(plan);
}
Assert.Contains("c.Name == \"Cylinders\"", flow.Code);
Assert.Contains("GetRobot(\"Robots\")", flow.Code);
Assert.Contains("r.Name == \"Robots\"", flow.Code);
Assert.Contains("GetConnect(\"Connects\")", flow.Code);
Assert.Contains("connectName: \"Connects\"", flow.Code);
Assert.Single(plans.Peek().ManualReferences);
Assert.Equal("Common", cylinder.InA);
while (plans.TryPop(out var plan)) p.ApplyRename(p.PlanUndo(Guid.NewGuid(), plan));
Assert.Equal(before, File.ReadAllBytes(Path.Combine(root.FullName, "configuration", "hardware.json")));
}
finally { root.Delete(true); }
}
}