From fc49db64a893bb538c58bc5214bbff137d5f1c1d Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 5 Dec 2026 22:25:25 +0800 Subject: [PATCH] Apply and undo reviewed device names and workflow edits in the live editor --- PLCSharp.Mcp/ProjectGateway.cs | 2 +- PLCSharp.Mcp/ProjectTools.cs | 4 ++ PLCSharpWpf/Models/DeviceRename.cs | 50 +++++++++++++++ PLCSharpWpf/Models/GlobalModel.Project.cs | 4 +- PLCSharpWpf/Models/IoRename.cs | 16 +++-- PLCSharpWpf/Models/PointRename.cs | 1 + PLCSharpWpf/Models/ProjectChanges.cs | 6 +- PLCSharpWpf/Models/VariableRename.cs | 14 +++- PLCSharpWpf/VVMs/Connects/Connect.cs | 4 +- PLCSharpWpf/VVMs/Cylinders/Cylinder.cs | 4 +- PLCSharpWpf/VVMs/Robots/Robot.cs | 4 +- .../VVMs/Workflows/ScriptReviewWindow.xaml.cs | 3 +- Tests/PLCSharp.Tests/DeviceRenameTests.cs | 64 +++++++++++++++++++ 13 files changed, 161 insertions(+), 15 deletions(-) create mode 100644 PLCSharpWpf/Models/DeviceRename.cs create mode 100644 Tests/PLCSharp.Tests/DeviceRenameTests.cs diff --git a/PLCSharp.Mcp/ProjectGateway.cs b/PLCSharp.Mcp/ProjectGateway.cs index 96ab9af..81d1959 100644 --- a/PLCSharp.Mcp/ProjectGateway.cs +++ b/PLCSharp.Mcp/ProjectGateway.cs @@ -28,7 +28,7 @@ internal sealed class ProjectGateway(string root, bool allowWrite) return ProjectPipe.Call(root, new() { ["operation"] = operation, ["arguments"] = arguments }, () => { 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 ProjectInspection.Query(project, operation, arguments); }).ToJsonString(); diff --git a/PLCSharp.Mcp/ProjectTools.cs b/PLCSharp.Mcp/ProjectTools.cs index f13a727..493a38e 100644 --- a/PLCSharp.Mcp/ProjectTools.cs +++ b/PLCSharp.Mcp/ProjectTools.cs @@ -11,6 +11,10 @@ internal sealed class ProjectTools(ProjectGateway gateway) public string PreviewVisionFunctionRename(string id, string 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.")] public string PreviewIoRename(string kind, string id, string newName) => gateway.Call("previewIoRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName }); diff --git a/PLCSharpWpf/Models/DeviceRename.cs b/PLCSharpWpf/Models/DeviceRename.cs new file mode 100644 index 0000000..f3b940c --- /dev/null +++ b/PLCSharpWpf/Models/DeviceRename.cs @@ -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 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); + } +} diff --git a/PLCSharpWpf/Models/GlobalModel.Project.cs b/PLCSharpWpf/Models/GlobalModel.Project.cs index 42b3ad5..18a832e 100644 --- a/PLCSharpWpf/Models/GlobalModel.Project.cs +++ b/PLCSharpWpf/Models/GlobalModel.Project.cs @@ -32,7 +32,7 @@ public partial class GlobalModel if (!AllowAiAccess) throw new InvalidOperationException("请在机种配方页面启用 AI 访问。"); string operation = (string)request["operation"]; 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)) throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); @@ -74,6 +74,8 @@ public partial class GlobalModel updateEditorView = Project.PrepareAxisView(axis, ControllersModel, CurrentRecipe.ID); if (accepted && change.Rename is { IsIo: true } io) updateEditorView = Project.PrepareIoView(io, ControllersModel, CylindersModel); + if (accepted && change.Rename is { IsDevice: true } device) + updateEditorView = PrepareDeviceView(device); return accepted; }); if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke(); diff --git a/PLCSharpWpf/Models/IoRename.cs b/PLCSharpWpf/Models/IoRename.cs index 81bfb9d..c579b53 100644 --- a/PLCSharpWpf/Models/IoRename.cs +++ b/PLCSharpWpf/Models/IoRename.cs @@ -12,14 +12,22 @@ public sealed partial class ProjectDirectory _ => 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) 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 && ((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) @@ -28,7 +36,7 @@ public sealed partial class ProjectDirectory CheckSavedRecipes(); var hardware = JsonNode.Parse(baseline[ConfigPath("hardware")]); 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(); foreach (var row in hardware["Cylinders"].AsArray()) foreach (var field in fields) diff --git a/PLCSharpWpf/Models/PointRename.cs b/PLCSharpWpf/Models/PointRename.cs index 0755a25..ab03dc0 100644 --- a/PLCSharpWpf/Models/PointRename.cs +++ b/PLCSharpWpf/Models/PointRename.cs @@ -12,6 +12,7 @@ public sealed record PointField(string Table, Guid Id, string Field) internal Type EntityType => Table switch { "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), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint), "Matrices" => typeof(Matrix), "RobotMatrices" => typeof(RobotMatrix), diff --git a/PLCSharpWpf/Models/ProjectChanges.cs b/PLCSharpWpf/Models/ProjectChanges.cs index 0401e36..a936938 100644 --- a/PLCSharpWpf/Models/ProjectChanges.cs +++ b/PLCSharpWpf/Models/ProjectChanges.cs @@ -26,10 +26,12 @@ public sealed class ProjectChanges public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, Func 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; - 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"]); else if (operation == "previewAxisRename") plan = project.PlanAxisRename(Guid.Parse((string)args["id"]), (string)args["newName"]); diff --git a/PLCSharpWpf/Models/VariableRename.cs b/PLCSharpWpf/Models/VariableRename.cs index 34ff63c..f70ba24 100644 --- a/PLCSharpWpf/Models/VariableRename.cs +++ b/PLCSharpWpf/Models/VariableRename.cs @@ -22,11 +22,12 @@ public sealed record ProjectRename(Guid ObjectId, Guid RecipeId, string OldName, { "AxisPoints" or "RobotPoints" => "configuration/points.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", _ => ProjectDirectory.VariablesPath }; public List MatrixReferences { get; init; } = []; + public bool IsDevice => Kind is "Cylinders" or "Robots" or "Connects"; public bool IsIo => Kind is "DI" or "DQ"; public List CylinderReferences { get; init; } = []; public List PointReferences { get; init; } = []; @@ -142,7 +143,7 @@ public sealed partial class ProjectDirectory { 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.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.IsPoint) ValidatePoint(plan, 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) .ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1) 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) .ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1) throw new ProjectConflictException("变量已发生变化。"); @@ -230,6 +231,13 @@ public sealed partial class ProjectDirectory configuration[plan.MetadataPath] = files[plan.MetadataPath]; if (plan.Kind == "Axes") 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") { AcceptPointFields(plan); diff --git a/PLCSharpWpf/VVMs/Connects/Connect.cs b/PLCSharpWpf/VVMs/Connects/Connect.cs index 984d266..abd6950 100644 --- a/PLCSharpWpf/VVMs/Connects/Connect.cs +++ b/PLCSharpWpf/VVMs/Connects/Connect.cs @@ -25,7 +25,7 @@ namespace PLCSharp.VVMs.Connects /// /// 连接 /// - public class Connect : BindableBase + public class Connect : BindableBase, PLCSharp.Models.INamedDevice { /// /// 唯一标识 @@ -42,6 +42,8 @@ namespace PLCSharp.VVMs.Connects private string _Name; + void PLCSharp.Models.INamedDevice.SetReviewedName(string value) => SetProperty(ref _Name, value, nameof(Name)); + /// /// 连接配置 /// diff --git a/PLCSharpWpf/VVMs/Cylinders/Cylinder.cs b/PLCSharpWpf/VVMs/Cylinders/Cylinder.cs index 426d6c4..74e3fc0 100644 --- a/PLCSharpWpf/VVMs/Cylinders/Cylinder.cs +++ b/PLCSharpWpf/VVMs/Cylinders/Cylinder.cs @@ -20,7 +20,7 @@ namespace PLCSharp.VVMs.Cylinders /// /// 气缸 /// - public class Cylinder : BindableBase + public class Cylinder : BindableBase, PLCSharp.Models.INamedDevice { /// /// 唯一标识 @@ -30,6 +30,8 @@ namespace PLCSharp.VVMs.Cylinders private string _Name; + void PLCSharp.Models.INamedDevice.SetReviewedName(string value) => SetProperty(ref _Name, value, nameof(Name)); + /// /// 气缸名称 /// diff --git a/PLCSharpWpf/VVMs/Robots/Robot.cs b/PLCSharpWpf/VVMs/Robots/Robot.cs index f77266e..e200ccc 100644 --- a/PLCSharpWpf/VVMs/Robots/Robot.cs +++ b/PLCSharpWpf/VVMs/Robots/Robot.cs @@ -13,7 +13,7 @@ namespace PLCSharp.VVMs.Robots /// /// 机器人 /// - public class Robot : BindableBase + public class Robot : BindableBase, PLCSharp.Models.INamedDevice { [NotMapped] public RobotModel Model { get; set; } @@ -26,6 +26,8 @@ namespace PLCSharp.VVMs.Robots private string _Name; + void PLCSharp.Models.INamedDevice.SetReviewedName(string value) => SetProperty(ref _Name, value, nameof(Name)); + /// /// 机器人名称 /// diff --git a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs index 42ab47b..34d4d00 100644 --- a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs +++ b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs @@ -11,7 +11,8 @@ public partial class ScriptReviewWindow : Window InitializeComponent(); 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" => "点位", _ => "变量" }; Title = $"确认{(rename.UndoOf.HasValue ? "撤销" : "")}{subject}重命名"; WorkflowTitle.Text = $"{rename.OldName} → {rename.NewName}"; diff --git a/Tests/PLCSharp.Tests/DeviceRenameTests.cs b/Tests/PLCSharp.Tests/DeviceRenameTests.cs new file mode 100644 index 0000000..bff643f --- /dev/null +++ b/Tests/PLCSharp.Tests/DeviceRenameTests.cs @@ -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(() => p.PlanDeviceRename("Robots", robot.ID, "Existing")); + var plans = new Stack(); + 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); } + } +}