From bd35b44d3502b579a87f3d4eddbd2fff1e27e8dc Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 5 Dec 2026 23:06:19 +0800 Subject: [PATCH] Connect object changes to reviewed MCP drafts and the live WPF models --- PLCSharp.Mcp/ProjectGateway.cs | 2 +- PLCSharp.Mcp/ProjectTools.cs | 4 + PLCSharpWpf/Models/GlobalModel.ObjectEdit.cs | 123 ++++++++++ PLCSharpWpf/Models/GlobalModel.Project.cs | 5 +- PLCSharpWpf/Models/ObjectEdit.cs | 14 +- PLCSharpWpf/Models/ProjectChanges.cs | 34 ++- PLCSharpWpf/VVMs/Connects/ConnectsModel.cs | 216 +++++++++--------- .../VVMs/MotionController/Controller.cs | 11 +- .../VVMs/MotionController/ControllersModel.cs | 27 ++- PLCSharpWpf/VVMs/Robots/Epson/EpsonRobot.cs | 11 +- PLCSharpWpf/VVMs/Robots/RobotModel.cs | 38 +-- PLCSharpWpf/VVMs/Vision/VisionsModel.cs | 13 ++ .../VVMs/Workflows/ScriptReviewWindow.xaml.cs | 19 +- 13 files changed, 377 insertions(+), 140 deletions(-) create mode 100644 PLCSharpWpf/Models/GlobalModel.ObjectEdit.cs diff --git a/PLCSharp.Mcp/ProjectGateway.cs b/PLCSharp.Mcp/ProjectGateway.cs index a36b844..820cff3 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 "previewVisionAssetRename" or "previewObjectRename" or "previewDeviceRename" 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 "previewVisionAssetRename" or "previewObjectEdit" or "previewObjectRename" 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 c911a9c..ae84ce0 100644 --- a/PLCSharp.Mcp/ProjectTools.cs +++ b/PLCSharp.Mcp/ProjectTools.cs @@ -7,6 +7,10 @@ namespace PLCSharp.Mcp; [McpServerToolType] internal sealed class ProjectTools(ProjectGateway gateway) { + [McpServerTool(Name = "preview_object_edit"), Description("Preview create, update or delete for Variables, AxisPoints, RobotPoints or hardware (Controllers, Axes, DI, DQ, Cylinders, Robots, Connects, Cameras). Use persisted JSON column names. Create generates an ID; pass RecipeID for scoped objects and RobotID for robot points. Update/delete require id. Objects in properties merge recursively, arrays replace. Review workflow/config references, dynamic references and compile results before apply_changes. Use preview_undo to reverse.")] + public string PreviewObjectEdit(string action, string kind, string id = null, JsonObject properties = null) => + gateway.Call("previewObjectEdit", new() { ["action"] = action, ["kind"] = kind, ["id"] = id, ["properties"] = properties?.DeepClone() }); + [McpServerTool(Name = "preview_vision_function_rename"), Description("Preview renaming a vision function by ID. Compile rewritten recipe workflows and list dynamic or uncertain references before applying.")] public string PreviewVisionFunctionRename(string id, string newName) => gateway.Call("previewVisionRename", new() { ["id"] = id, ["newName"] = newName }); diff --git a/PLCSharpWpf/Models/GlobalModel.ObjectEdit.cs b/PLCSharpWpf/Models/GlobalModel.ObjectEdit.cs new file mode 100644 index 0000000..bf87d7d --- /dev/null +++ b/PLCSharpWpf/Models/GlobalModel.ObjectEdit.cs @@ -0,0 +1,123 @@ +using System.Collections; +using System.Text.Json.Nodes; +using Microsoft.EntityFrameworkCore; +using PLCSharp.VVMs.Cylinders; +using PLCSharp.VVMs.Connects; +using PLCSharp.VVMs.GlobalVariables; +using PLCSharp.VVMs.MotionController; +using PLCSharp.VVMs.Robots; +using PLCSharp.VVMs.Robots.Epson; +using PLCSharp.VVMs.Vision.Camera; + +namespace PLCSharp.Models; + +public partial class GlobalModel +{ + private Action PrepareObjectView(ObjectEdit edit) + { + var row = edit.After ?? edit.Before; + if (row["RecipeID"] != null && Guid.Parse((string)row["RecipeID"]) != CurrentRecipe.ID) return null; + Robot robot = edit.Kind == "RobotPoints" ? RobotModel.Robots.SingleOrDefault(r => r.ID == Guid.Parse((string)row["RobotID"])) : null; + var controller = ControllersModel.Controller; + var entity = ProjectConfiguration.Entity(Project.Data, edit.Kind); + var key = entity.FindPrimaryKey().Properties.Single().PropertyInfo; + IList list = edit.Kind switch + { + "Variables" => VariablesModel.Variables, "AxisPoints" => ControllersModel.AxisPoints, + "RobotPoints" => robot?.Points, "Axes" => ControllersModel.Axes, "DI" => ControllersModel.DI, + "DQ" => ControllersModel.DQ, "Robots" => RobotModel.Robots, "Cylinders" => CylindersModel.Cylinders, + "Cameras" => VisionsModel.Cameras, "Connects" => Connects.Connects, _ => null + }; + object live = edit.Kind == "Controllers" ? controller : list?.Cast().SingleOrDefault(o => (Guid)key.GetValue(o) == edit.Id); + var properties = entity.GetProperties().Where(p => edit.Before == null || edit.After == null || + !JsonNode.DeepEquals(edit.Before[p.GetColumnName()], edit.After[p.GetColumnName()])).ToArray(); + if (edit.Before != null && live != null) + { + var before = ProjectDirectory.ObjectRow(entity, ProjectDirectory.MaterializeObject(entity, edit.Before)); + var current = ProjectDirectory.ObjectRow(entity, live); + foreach (var p in properties) + if (!JsonNode.DeepEquals(before[p.GetColumnName()], current[p.GetColumnName()])) + throw new ProjectConflictException($"编辑器中 {p.GetColumnName()} 有未保存的修改。"); + } + if (live is Connect { Connected: true } or CameraBase { Connected: true } || + live is EpsonRobot epson && (epson.ClientCtrl.Connected || epson.ClientCommand.Connected) || + (edit.Kind is "Controllers" or "Axes" or "DI" or "DQ") && controller.Connected) + throw new ProjectConflictException("请先断开正在使用的设备连接。"); + + var next = edit.After == null ? null : ProjectDirectory.MaterializeObject(entity, edit.After); + void ApplyFields(object target) + { + foreach (var p in properties) p.PropertyInfo.SetValue(target, p.PropertyInfo.GetValue(next)); + } + void Remove() + { + if (live != null) list?.Remove(live); + } + return () => + { + if (edit.Kind == "Controllers") + { + if (next == null || edit.Before == null || properties.Any(p => p.Name == "Type")) controller.ForgetReviewedDriver(); + if (next != null) ApplyFields(controller); + else + { + var empty = new Controller(); + foreach (var p in properties) p.PropertyInfo.SetValue(controller, p.PropertyInfo.GetValue(empty)); + } + return; + } + if (list == null) return; // A saved robot point may belong to a robot without a configured driver. + if (edit.Kind == "Connects") + { + if (Connects.SelectedConnect == live) Connects.SelectedConnect = null; + Remove(); + if (next != null) Connects.AddConfigured((Connect)next); + return; + } + if (edit.Kind == "Robots") + { + if (live is EpsonRobot old) old.EndPolling(); + Remove(); + if (next is Robot { Type: RobotType.Epson } definition) + { + var r = EpsonRobot.Create(definition); + foreach (var p in entity.GetProperties()) p.PropertyInfo.SetValue(r, p.PropertyInfo.GetValue(definition)); + r.Model = RobotModel; + RobotModel.Robots.Add(r); + RobotModel.LoadReviewedPoints(r, CurrentRecipe.ID); + } + return; + } + if (edit.Kind == "Variables" || edit.Kind == "Cylinders") + { + var tracked = next == null ? null : Project.Data.Find(entity.ClrType, edit.Id); + if (tracked is Variable variable) variable.RestoreValue(Project.Data); + if (tracked == null) Remove(); + else if (live == null) list.Add(tracked); + if (edit.Kind == "Variables" && next == null && VariablesModel.SelectedVariable == live) VariablesModel.SelectedVariable = null; + return; + } + IList channels = edit.Kind switch { "Axes" => controller.Axes, "DI" => controller.DI, "DQ" => controller.DQ, _ => null }; + if (next == null) + { + Remove(); + if (live != null) channels?.Remove(live); + if (live != null && ControllersModel.SelectedAxis == live) ControllersModel.SelectedAxis = null; + if (live != null && ControllersModel.SelectedAxisPoint == live) ControllersModel.SelectedAxisPoint = null; + if (live != null && robot?.SelectedPoint == live) robot.SelectedPoint = null; + if (live != null && VisionsModel.SelectedCamera == live) VisionsModel.SelectedCamera = null; + } + else if (live == null) + { + live = next is CameraBase camera ? VisionsModel.ReviewedCamera(camera) : next; + list.Add(live); + channels?.Add(live); + } + else ApplyFields(live); + if (edit.Kind is "AxisPoints" or "Axes") ControllersModel.RefreshReviewedAxes(edit.Kind, edit.Id, (string)row["Name"]); + if (edit.Kind == "RobotPoints") + foreach (var matrix in robot.RobotMatrices.Where(m => m.StartName == (string)row["Name"] || m.XEndName == (string)row["Name"] || m.YEndName == (string)row["Name"])) + robot.Create(matrix); + }; + } +} diff --git a/PLCSharpWpf/Models/GlobalModel.Project.cs b/PLCSharpWpf/Models/GlobalModel.Project.cs index 1c83ad8..b5d853b 100644 --- a/PLCSharpWpf/Models/GlobalModel.Project.cs +++ b/PLCSharpWpf/Models/GlobalModel.Project.cs @@ -32,14 +32,14 @@ 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 "previewVisionAssetRename" or "previewObjectRename" or "previewDeviceRename" 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 "previewVisionAssetRename" or "previewObjectEdit" or "previewObjectRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status") { if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy)) throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); Action updateEditorView = null; var resultChange = aiChanges.Execute(Project, operation, args, true, change => { - bool accepted = change.Review != null || change.Rename != null + bool accepted = change.Review != null || change.Rename != null || change.Edit != null ? PLCSharp.VVMs.Workflows.ScriptReviewWindow.Confirm(change, Project.Root, Application.Current.MainWindow) : MessageBox.Show($"{change.Path}\n{change.Kind} / {change.Name}\n\n原备注:{change.Before}\n新备注:{change.After}", "应用 AI 修改", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes; @@ -98,6 +98,7 @@ public partial class GlobalModel updateEditorView = Project.PrepareAssetView(asset, VisionsModel, CurrentRecipe.ID, CustomControls, VariablesModel.SystemVariables); if (accepted && change.Rename is { IsDevice: true } device) updateEditorView = PrepareDeviceView(device); + if (accepted && change.Edit != null) updateEditorView = PrepareObjectView(change.Edit); return accepted; }); if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke(); diff --git a/PLCSharpWpf/Models/ObjectEdit.cs b/PLCSharpWpf/Models/ObjectEdit.cs index 660307d..7fee937 100644 --- a/PLCSharpWpf/Models/ObjectEdit.cs +++ b/PLCSharpWpf/Models/ObjectEdit.cs @@ -164,6 +164,17 @@ public sealed partial class ProjectDirectory (string)r["RecipeID"] == (string)after["RecipeID"] && (string)r["RobotID"] == (string)after["RobotID"])) throw new ArgumentException("名称为空、带首尾空白或在所属范围内重名。"); } + if (kind == "Variables" && (Changed("Type") || Changed("DefaultValueStr") || Changed("ValueStr"))) + { + foreach (var field in new[] { "DefaultValueStr", "ValueStr" }) + { + var text = (string)after[field]; + if (!string.IsNullOrEmpty(text) && ((int)after["Type"] switch + { + 0 => !int.TryParse(text, out _), 1 => !double.TryParse(text, out var number) || !double.IsFinite(number), _ => false + })) throw new ArgumentException($"{field} 与变量类型不匹配。"); + } + } var address = kind switch { "Axes" => "AxisNo", "DI" or "DQ" => "Number", _ => null }; if (address != null && Changed(address) && rows.Any(r => Other(r) && JsonNode.DeepEquals(r[address], after[address]))) throw new ArgumentException($"{address} 在同类设备中重复。"); @@ -208,7 +219,8 @@ public sealed partial class ProjectDirectory else { // ObjectGroup validates the table against the fixed project schema. - if (Data.Database.ExecuteSqlRaw($"DELETE FROM \"{edit.Kind}\" WHERE ID = {{0}}", edit.Id) != 1) + string sql = $"DELETE FROM \"{edit.Kind}\" WHERE ID = {{0}}"; + if (Data.Database.ExecuteSqlRaw(sql, edit.Id) != 1) throw new ProjectConflictException("对象已删除。"); } WriteFiles(Root, files, baseline.Keys.ToArray(), tx.Commit); diff --git a/PLCSharpWpf/Models/ProjectChanges.cs b/PLCSharpWpf/Models/ProjectChanges.cs index 627c247..87586d7 100644 --- a/PLCSharpWpf/Models/ProjectChanges.cs +++ b/PLCSharpWpf/Models/ProjectChanges.cs @@ -7,14 +7,14 @@ using System.Text.Json.Nodes; namespace PLCSharp.Models; public sealed record ProjectChange(Guid DraftId, Guid ProjectId, string Kind, Guid ObjectId, Guid RecipeId, - string Name, string Path, string Before, string After, string Revision, string Status, WorkflowScriptReview Review = null, ProjectRename Rename = null); + string Name, string Path, string Before, string After, string Revision, string Status, WorkflowScriptReview Review = null, ProjectRename Rename = null, ObjectEdit Edit = null); public sealed class ProjectChanges { private readonly Dictionary drafts = new(); public ProjectChange PendingScript(Guid id) => - drafts.TryGetValue(id, out var draft) && (draft.Review != null || draft.Rename != null) && draft.Status == "pending" ? draft : null; + drafts.TryGetValue(id, out var draft) && (draft.Review != null || draft.Rename != null || draft.Edit != null) && draft.Status == "pending" ? draft : null; private JsonNode Remember(ProjectChange change) { @@ -26,6 +26,25 @@ public sealed class ProjectChanges public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, Func confirm = null) { + ObjectEdit edit = null; + if (operation == "previewObjectEdit") + edit = project.PlanObjectEdit((string)args["action"], (string)args["kind"], + args["id"] == null ? null : Guid.Parse((string)args["id"]), args["properties"]?.AsObject()); + if (operation == "previewUndo" && drafts.TryGetValue(Guid.Parse((string)args["draftId"]), out var previousEdit) && + previousEdit.Edit != null) + { + if (previousEdit.ProjectId != project.Id || previousEdit.Status != "saved" || previousEdit.Edit.UndoOf.HasValue) + throw new ProjectConflictException("需要当前工程中已保存且尚未撤销的对象修改。"); + edit = project.UndoObject(previousEdit.DraftId, previousEdit.Edit); + } + if (edit != null) + { + var row = edit.After ?? edit.Before; + return Remember(new(Guid.NewGuid(), project.Id, edit.Kind, edit.Id, + Guid.TryParse((string)row["RecipeID"], out var recipe) ? recipe : Guid.Empty, + (string)row["Name"] ?? edit.Kind, edit.Path, null, null, project.Revision(edit.Path), + edit.Compiled ? "pending" : "invalid", Edit: edit)); + } if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectRename" or "previewDeviceRename" or "previewUndo") { ProjectRename plan; @@ -93,13 +112,20 @@ public sealed class ProjectChanges if (operation == "apply" && draft.Status == "pending") { if (!allowWrite) throw new InvalidOperationException("Start the MCP server with --allow-write to apply a preview."); - if ((draft.Review != null || draft.Rename != null) && confirm == null) throw new InvalidOperationException("脚本修改需要用户确认。"); + if ((draft.Review != null || draft.Rename != null || draft.Edit != null) && confirm == null) throw new InvalidOperationException("脚本修改需要用户确认。"); if (confirm != null && !confirm(draft)) draft = draft with { Status = "rejected" }; else { try { - if (draft.Rename != null) + if (draft.Edit != null) + { + if (draft.Edit.UndoOf is Guid source && (!drafts.TryGetValue(source, out var orig) || orig.Status != "saved")) + throw new ProjectConflictException("原操作已经撤销。"); + project.ApplyObjectEdit(draft.Edit); + if (draft.Edit.UndoOf is Guid previous) drafts[previous] = drafts[previous] with { Status = "undone" }; + } + else if (draft.Rename != null) { if (draft.Rename.UndoOf is Guid source && (!drafts.TryGetValue(source, out var original) || original.Status != "saved")) diff --git a/PLCSharpWpf/VVMs/Connects/ConnectsModel.cs b/PLCSharpWpf/VVMs/Connects/ConnectsModel.cs index ac3dc3a..08275d6 100644 --- a/PLCSharpWpf/VVMs/Connects/ConnectsModel.cs +++ b/PLCSharpWpf/VVMs/Connects/ConnectsModel.cs @@ -1,4 +1,4 @@ -using DryIoc; +using DryIoc; using PLCSharp.Core.Prism; using PLCSharp.Models; using PLCSharp.VVMs.Connects.ModbusTcp; @@ -32,126 +32,128 @@ namespace PLCSharp.VVMs.Connects if (!_pollWorker.IsBusy) _pollWorker.RunWorkerAsync(); - foreach (var item in _DatasContext.Connects) + foreach (var item in _DatasContext.Connects) AddConfigured(item); + } + + internal void AddConfigured(Connect item) + { + switch (item.Type) { - switch (item.Type) - { - case ProtocolType.SocketClient: + case ProtocolType.SocketClient: + { + var connect = new SocketClient { - var connect = new SocketClient - { - ID = item.ID, - Name = item.Name, - IP_SerialPort = item.IP_SerialPort, - Port = item.Port, - Type = item.Type, - Comment = item.Comment, - Params = item.Params, - }; - connect.Params.Prompt = ""; - Connects.Add(connect); - } - break; + ID = item.ID, + Name = item.Name, + IP_SerialPort = item.IP_SerialPort, + Port = item.Port, + Type = item.Type, + Comment = item.Comment, + Params = item.Params, + }; + connect.Params.Prompt = ""; + Connects.Add(connect); + } + break; - case ProtocolType.SocketSever: + case ProtocolType.SocketSever: + { + var connect = new SocketServer { - var connect = new SocketServer - { - ID = item.ID, - Name = item.Name, - IP_SerialPort = item.IP_SerialPort, - Port = item.Port, - Type = item.Type, - Comment = item.Comment, - Clients = item.Clients, - Params = item.Params, - }; - connect.Params.Prompt = ""; - connect.Clients.ToList().ForEach(c => c.Params.Prompt = ""); - Connects.Add(connect); - } - break; + ID = item.ID, + Name = item.Name, + IP_SerialPort = item.IP_SerialPort, + Port = item.Port, + Type = item.Type, + Comment = item.Comment, + Clients = item.Clients, + Params = item.Params, + }; + connect.Params.Prompt = ""; + connect.Clients.ToList().ForEach(c => c.Params.Prompt = ""); + Connects.Add(connect); + } + break; - case ProtocolType.ModbusTcpClient: + case ProtocolType.ModbusTcpClient: + { + var connect = new ModbusTcp.ModbusTcpClient { - var connect = new ModbusTcp.ModbusTcpClient - { - ID = item.ID, - Name = item.Name, - IP_SerialPort = item.IP_SerialPort, - Port = item.Port, - Type = item.Type, - Comment = item.Comment, - Params = item.Params, - DataItems = item.DataItems, - }; - connect.Params.Prompt = ""; - Connects.Add(connect); - } - break; + ID = item.ID, + Name = item.Name, + IP_SerialPort = item.IP_SerialPort, + Port = item.Port, + Type = item.Type, + Comment = item.Comment, + Params = item.Params, + DataItems = item.DataItems, + }; + connect.Params.Prompt = ""; + Connects.Add(connect); + } + break; - case ProtocolType.ModbusTcpServer: + case ProtocolType.ModbusTcpServer: + { + var connect = new ModbusTcp.ModbusTcpServer { - var connect = new ModbusTcp.ModbusTcpServer - { - ID = item.ID, - Name = item.Name, - IP_SerialPort = item.IP_SerialPort, - Port = item.Port, - Type = item.Type, - Comment = item.Comment, - Clients = item.Clients, - Params = item.Params, - DataItems = item.DataItems, - }; - connect.Params.Prompt = ""; + ID = item.ID, + Name = item.Name, + IP_SerialPort = item.IP_SerialPort, + Port = item.Port, + Type = item.Type, + Comment = item.Comment, + Clients = item.Clients, + Params = item.Params, + DataItems = item.DataItems, + }; + connect.Params.Prompt = ""; - Connects.Add(connect); - // 加载时将 DataItems 同步到服务端内存数据表 - ApplyAllDataToServer(connect); - } - break; + Connects.Add(connect); + // 加载时将 DataItems 同步到服务端内存数据表 + ApplyAllDataToServer(connect); + } + break; - case ProtocolType.ModbusRtuClient: + case ProtocolType.ModbusRtuClient: + { + var connect = new ModbusRtu.ModbusRtuClient { - var connect = new ModbusRtu.ModbusRtuClient - { - ID = item.ID, - Name = item.Name, - IP_SerialPort = item.IP_SerialPort, - Port = item.Port, - Type = item.Type, - Comment = item.Comment, - Params = item.Params, - DataItems = item.DataItems, - }; - connect.Params.Prompt = ""; - Connects.Add(connect); - } - break; + ID = item.ID, + Name = item.Name, + IP_SerialPort = item.IP_SerialPort, + Port = item.Port, + Type = item.Type, + Comment = item.Comment, + Params = item.Params, + DataItems = item.DataItems, + }; + connect.Params.Prompt = ""; + Connects.Add(connect); + } + break; - case ProtocolType.FreeSerialProtocol: + case ProtocolType.FreeSerialProtocol: + { + var connect = new SerialPort.FreeSerialProtocol { - var connect = new SerialPort.FreeSerialProtocol - { - ID = item.ID, - Name = item.Name, - IP_SerialPort = item.IP_SerialPort, - Port = item.Port, - Type = item.Type, - Comment = item.Comment, - Params = item.Params, - DataItems = item.DataItems, - }; - connect.Params.Prompt = ""; - Connects.Add(connect); - } - break; + ID = item.ID, + Name = item.Name, + IP_SerialPort = item.IP_SerialPort, + Port = item.Port, + Type = item.Type, + Comment = item.Comment, + Params = item.Params, + DataItems = item.DataItems, + }; + connect.Params.Prompt = ""; + Connects.Add(connect); + } + break; - default: - SendErr("未配置的协议"); - break; - } + default: + SendErr("未配置的协议"); + break; } } diff --git a/PLCSharpWpf/VVMs/MotionController/Controller.cs b/PLCSharpWpf/VVMs/MotionController/Controller.cs index 8c9f3fb..e390dbf 100644 --- a/PLCSharpWpf/VVMs/MotionController/Controller.cs +++ b/PLCSharpWpf/VVMs/MotionController/Controller.cs @@ -1,4 +1,4 @@ -using PLCSharp.Core.Prism; +using PLCSharp.Core.Prism; using PLCSharp.Core.Tools; using PLCSharp.Models; using Prism.Commands; @@ -419,6 +419,15 @@ namespace PLCSharp.VVMs.MotionController } } + internal void ForgetReviewedDriver() + { + Type = ControllerType.Undefined; + SDK?.Close(); + SDK = null; + Connected = false; + Online = false; + } + private ControllerSDK SDK; private BackgroundWorker bkgWorker; private string _IP; diff --git a/PLCSharpWpf/VVMs/MotionController/ControllersModel.cs b/PLCSharpWpf/VVMs/MotionController/ControllersModel.cs index 637603c..93f87be 100644 --- a/PLCSharpWpf/VVMs/MotionController/ControllersModel.cs +++ b/PLCSharpWpf/VVMs/MotionController/ControllersModel.cs @@ -1,4 +1,4 @@ -using MiniExcelLibs; +using MiniExcelLibs; using PLCSharp.Core.Prism; using PLCSharp.Core.Tools; using PLCSharp.Models; @@ -1615,6 +1615,31 @@ namespace PLCSharp.VVMs.MotionController } } + internal void RefreshReviewedAxes(string kind, Guid id, string name) + { + void Bind(string axisName, Action bind, Action restoreName) + { + if (kind == "Axes" && axisName != name) return; + bind(Axes.FirstOrDefault(a => a.Name == axisName)); + restoreName(axisName); + } + foreach (var point in AxisPoints.Where(p => kind == "Axes" || p.ID == id)) + { + Bind(point.AxisXName, a => point.AxisX = a, n => point.AxisXName = n); + Bind(point.AxisYName, a => point.AxisY = a, n => point.AxisYName = n); + Bind(point.AxisZName, a => point.AxisZ = a, n => point.AxisZName = n); + Bind(point.AxisUName, a => point.AxisU = a, n => point.AxisUName = n); + } + if (kind == "Axes") + foreach (var group in InterpolationGroups) + { + Bind(group.AxisXName, a => group.AxisX = a, n => group.AxisXName = n); + Bind(group.AxisYName, a => group.AxisY = a, n => group.AxisYName = n); + } + foreach (var matrix in Matrices.Where(m => kind == "Axes" || m.StartName == name || m.XEndName == name || m.YEndName == name)) + Create(matrix); + } + internal void LoadRecipe(Guid CurrentRecipeID) { Stop(); diff --git a/PLCSharpWpf/VVMs/Robots/Epson/EpsonRobot.cs b/PLCSharpWpf/VVMs/Robots/Epson/EpsonRobot.cs index 4ac0a6c..e500550 100644 --- a/PLCSharpWpf/VVMs/Robots/Epson/EpsonRobot.cs +++ b/PLCSharpWpf/VVMs/Robots/Epson/EpsonRobot.cs @@ -1,4 +1,4 @@ -using PLCSharp.Core.Tools; +using PLCSharp.Core.Tools; using PLCSharp.VVMs.Connects.Socket; using System.Threading; @@ -57,6 +57,9 @@ public class EpsonRobot : Robot return r; } + private volatile bool pollingStopped; + internal void EndPolling() => pollingStopped = true; + private void ConnectRobot() { // 启动状态轮询线程 @@ -72,7 +75,7 @@ public class EpsonRobot : Robot private void ReceivesRunState() { - while (true) + while (!pollingStopped) { Thread.Sleep(1000); try @@ -165,7 +168,7 @@ public class EpsonRobot : Robot private void ReceivesRemoteState() { - while (true) + while (!pollingStopped) try { Status[13] = false; @@ -173,7 +176,7 @@ public class EpsonRobot : Robot if (Status[14] && !ClientCommand.Connected) continue; ClientCommand.SendMsg("@ReturnHere,0\r\n"); Status[13] = true; - while (ClientCommand.Connected && Status[13]) + while (!pollingStopped && ClientCommand.Connected && Status[13]) { Thread.Sleep(10); try diff --git a/PLCSharpWpf/VVMs/Robots/RobotModel.cs b/PLCSharpWpf/VVMs/Robots/RobotModel.cs index 55d119f..7eeeb18 100644 --- a/PLCSharpWpf/VVMs/Robots/RobotModel.cs +++ b/PLCSharpWpf/VVMs/Robots/RobotModel.cs @@ -1,4 +1,4 @@ -using PLCSharp.Core.Prism; +using PLCSharp.Core.Prism; using PLCSharp.Core.Tools; using PLCSharp.Models; using PLCSharp.VVMs.Robots.Epson; @@ -88,29 +88,31 @@ namespace PLCSharp.VVMs.Robots public void LoadRecipe(Guid CurrentRecipeID) { - foreach (var robot in Robots) + foreach (var robot in Robots) LoadReviewedPoints(robot, CurrentRecipeID); + } + + internal void LoadReviewedPoints(Robot robot, Guid CurrentRecipeID) + { + robot.Points.Clear(); + + foreach (var item in _DatasContext.RobotPoints) { - robot.Points.Clear(); - - foreach (var item in _DatasContext.RobotPoints) + if (item.RobotID == robot.ID && item.RecipeID == CurrentRecipeID) { - if (item.RobotID == robot.ID && item.RecipeID == CurrentRecipeID) - { - var point = item.DeepCopy(); + var point = item.DeepCopy(); - robot.Points.Add(point); - } + robot.Points.Add(point); } + } - robot.RobotMatrices.Clear(); - foreach (var item in _DatasContext.RobotMatrices) + robot.RobotMatrices.Clear(); + foreach (var item in _DatasContext.RobotMatrices) + { + if (item.RobotID == robot.ID && item.RecipeID == CurrentRecipeID) { - if (item.RobotID == robot.ID && item.RecipeID == CurrentRecipeID) - { - var matrix = item.DeepCopy(); - robot.Create(matrix); - robot.RobotMatrices.Add(matrix); - } + var matrix = item.DeepCopy(); + robot.Create(matrix); + robot.RobotMatrices.Add(matrix); } } } diff --git a/PLCSharpWpf/VVMs/Vision/VisionsModel.cs b/PLCSharpWpf/VVMs/Vision/VisionsModel.cs index b36363b..8e5e28a 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionsModel.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionsModel.cs @@ -234,6 +234,19 @@ namespace PLCSharp.VVMs.Vision #region Camera + internal CameraBase ReviewedCamera(CameraBase definition) + { + var discovery = definition.Params.DiscoveryName ?? definition.Name; + var camera = _HikCameras.Cameras.FirstOrDefault(c => (c.Params.DiscoveryName ?? c.Name) == discovery); + if (camera == null) return definition; + camera.ID = definition.ID; + camera.Name = definition.Name; + camera.Comment = definition.Comment; + camera.Params = definition.Params; + camera.Prompt = ""; + return camera; + } + private readonly HikCameras _HikCameras; private ObservableCollection _Cameras = []; diff --git a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs index b450e55..8d3bbf3 100644 --- a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs +++ b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs @@ -9,7 +9,24 @@ public partial class ScriptReviewWindow : Window private ScriptReviewWindow(ProjectChange change, string root) { InitializeComponent(); - if (change.Rename is { } rename) + if (change.Edit is { } edit) + { + string action = edit.Action switch { "create" => "新增", "update" => "修改", _ => "删除" }; + Title = $"确认{(edit.UndoOf.HasValue ? "撤销 · " : "")}{action}工程对象"; + WorkflowTitle.Text = $"{edit.Kind} · {change.Name} · {edit.Id}"; + Location.Text = System.IO.Path.Combine(root, edit.Path); + CheckResult.Text = $"已编译工作流 {edit.Workflows.Count},工作流引用 {edit.WorkflowReferences.Count},配置引用 {edit.ConfigReferences.Count},待核对 {edit.ManualReferences.Count}"; + var lines = new List(); + foreach (var hit in edit.WorkflowReferences) lines.Add($"工作流 {hit["Name"]} · {hit["path"]}:{hit["line"]} {hit["expression"]}"); + foreach (var link in edit.ConfigReferences) lines.Add($"配置 {link["path"]} · {link["table"]}/{link["id"]} · {link["field"]}"); + foreach (var hit in edit.ManualReferences) lines.Add($"待核对 [{hit["confidence"]}] {hit["path"]}:{hit["line"]} {hit["expression"]}"); + if (edit.Action == "delete" && lines.Count > 0) lines.Add("确认删除将保留上列引用,请核对删除后的影响。"); + foreach (var key in (edit.Before ?? edit.After).Select(k => k.Key)) + if (!System.Text.Json.Nodes.JsonNode.DeepEquals(edit.Before?[key], edit.After?[key])) + lines.Add($"{key}:{edit.Before?[key]} → {edit.After?[key]}"); + CodeDiff.Text = string.Join("\n", lines); + } + else if (change.Rename is { } rename) { var subject = rename.Kind switch { "VisionLocalVariables" => "视觉局部变量", "ControlMeasurements" => "控件测量项", "InterpolationSegments" => "插补段", "InterpolationPoints" => "插补段内点", "Recipes" => "配方", "SystemVariables" => "系统变量", "CustomControls" => "主页控件",