Connect object changes to reviewed MCP drafts and the live WPF models

This commit is contained in:
wanglei 2026-12-05 23:06:19 +08:00
parent 9f22a36a0b
commit bd35b44d35
13 changed files with 377 additions and 140 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 "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 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

@ -7,6 +7,10 @@ namespace PLCSharp.Mcp;
[McpServerToolType] [McpServerToolType]
internal sealed class ProjectTools(ProjectGateway gateway) 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.")] [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) => public string PreviewVisionFunctionRename(string id, string newName) =>
gateway.Call("previewVisionRename", new() { ["id"] = id, ["newName"] = newName }); gateway.Call("previewVisionRename", new() { ["id"] = id, ["newName"] = newName });

View File

@ -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<object>().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);
};
}
}

View File

@ -32,14 +32,14 @@ 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 "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)) if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy))
throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。");
Action updateEditorView = null; Action updateEditorView = null;
var resultChange = aiChanges.Execute(Project, operation, args, true, change => 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) ? 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}", : 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; "应用 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); updateEditorView = Project.PrepareAssetView(asset, VisionsModel, CurrentRecipe.ID, CustomControls, VariablesModel.SystemVariables);
if (accepted && change.Rename is { IsDevice: true } device) if (accepted && change.Rename is { IsDevice: true } device)
updateEditorView = PrepareDeviceView(device); updateEditorView = PrepareDeviceView(device);
if (accepted && change.Edit != null) updateEditorView = PrepareObjectView(change.Edit);
return accepted; return accepted;
}); });
if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke(); if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke();

View File

@ -164,6 +164,17 @@ public sealed partial class ProjectDirectory
(string)r["RecipeID"] == (string)after["RecipeID"] && (string)r["RobotID"] == (string)after["RobotID"])) (string)r["RecipeID"] == (string)after["RecipeID"] && (string)r["RobotID"] == (string)after["RobotID"]))
throw new ArgumentException("名称为空、带首尾空白或在所属范围内重名。"); 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 }; 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]))) if (address != null && Changed(address) && rows.Any(r => Other(r) && JsonNode.DeepEquals(r[address], after[address])))
throw new ArgumentException($"{address} 在同类设备中重复。"); throw new ArgumentException($"{address} 在同类设备中重复。");
@ -208,7 +219,8 @@ public sealed partial class ProjectDirectory
else else
{ {
// ObjectGroup validates the table against the fixed project schema. // 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("对象已删除。"); throw new ProjectConflictException("对象已删除。");
} }
WriteFiles(Root, files, baseline.Keys.ToArray(), tx.Commit); WriteFiles(Root, files, baseline.Keys.ToArray(), tx.Commit);

View File

@ -7,14 +7,14 @@ using System.Text.Json.Nodes;
namespace PLCSharp.Models; namespace PLCSharp.Models;
public sealed record ProjectChange(Guid DraftId, Guid ProjectId, string Kind, Guid ObjectId, Guid RecipeId, 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 public sealed class ProjectChanges
{ {
private readonly Dictionary<Guid, ProjectChange> drafts = new(); private readonly Dictionary<Guid, ProjectChange> drafts = new();
public ProjectChange PendingScript(Guid id) => 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) private JsonNode Remember(ProjectChange change)
{ {
@ -26,6 +26,25 @@ 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)
{ {
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") if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectRename" or "previewDeviceRename" or "previewUndo")
{ {
ProjectRename plan; ProjectRename plan;
@ -93,13 +112,20 @@ public sealed class ProjectChanges
if (operation == "apply" && draft.Status == "pending") if (operation == "apply" && draft.Status == "pending")
{ {
if (!allowWrite) throw new InvalidOperationException("Start the MCP server with --allow-write to apply a preview."); 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" }; if (confirm != null && !confirm(draft)) draft = draft with { Status = "rejected" };
else else
{ {
try 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 && if (draft.Rename.UndoOf is Guid source &&
(!drafts.TryGetValue(source, out var original) || original.Status != "saved")) (!drafts.TryGetValue(source, out var original) || original.Status != "saved"))

View File

@ -1,4 +1,4 @@
using DryIoc; using DryIoc;
using PLCSharp.Core.Prism; using PLCSharp.Core.Prism;
using PLCSharp.Models; using PLCSharp.Models;
using PLCSharp.VVMs.Connects.ModbusTcp; using PLCSharp.VVMs.Connects.ModbusTcp;
@ -32,126 +32,128 @@ namespace PLCSharp.VVMs.Connects
if (!_pollWorker.IsBusy) if (!_pollWorker.IsBusy)
_pollWorker.RunWorkerAsync(); _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,
ID = item.ID, IP_SerialPort = item.IP_SerialPort,
Name = item.Name, Port = item.Port,
IP_SerialPort = item.IP_SerialPort, Type = item.Type,
Port = item.Port, Comment = item.Comment,
Type = item.Type, Params = item.Params,
Comment = item.Comment, };
Params = item.Params, connect.Params.Prompt = "";
}; Connects.Add(connect);
connect.Params.Prompt = ""; }
Connects.Add(connect); break;
}
break;
case ProtocolType.SocketSever: case ProtocolType.SocketSever:
{
var connect = new SocketServer
{ {
var connect = new SocketServer ID = item.ID,
{ Name = item.Name,
ID = item.ID, IP_SerialPort = item.IP_SerialPort,
Name = item.Name, Port = item.Port,
IP_SerialPort = item.IP_SerialPort, Type = item.Type,
Port = item.Port, Comment = item.Comment,
Type = item.Type, Clients = item.Clients,
Comment = item.Comment, Params = item.Params,
Clients = item.Clients, };
Params = item.Params, connect.Params.Prompt = "";
}; connect.Clients.ToList().ForEach(c => c.Params.Prompt = "");
connect.Params.Prompt = ""; Connects.Add(connect);
connect.Clients.ToList().ForEach(c => c.Params.Prompt = ""); }
Connects.Add(connect); break;
}
break;
case ProtocolType.ModbusTcpClient: case ProtocolType.ModbusTcpClient:
{
var connect = new ModbusTcp.ModbusTcpClient
{ {
var connect = new ModbusTcp.ModbusTcpClient ID = item.ID,
{ Name = item.Name,
ID = item.ID, IP_SerialPort = item.IP_SerialPort,
Name = item.Name, Port = item.Port,
IP_SerialPort = item.IP_SerialPort, Type = item.Type,
Port = item.Port, Comment = item.Comment,
Type = item.Type, Params = item.Params,
Comment = item.Comment, DataItems = item.DataItems,
Params = item.Params, };
DataItems = item.DataItems, connect.Params.Prompt = "";
}; Connects.Add(connect);
connect.Params.Prompt = ""; }
Connects.Add(connect); break;
}
break;
case ProtocolType.ModbusTcpServer: case ProtocolType.ModbusTcpServer:
{
var connect = new ModbusTcp.ModbusTcpServer
{ {
var connect = new ModbusTcp.ModbusTcpServer ID = item.ID,
{ Name = item.Name,
ID = item.ID, IP_SerialPort = item.IP_SerialPort,
Name = item.Name, Port = item.Port,
IP_SerialPort = item.IP_SerialPort, Type = item.Type,
Port = item.Port, Comment = item.Comment,
Type = item.Type, Clients = item.Clients,
Comment = item.Comment, Params = item.Params,
Clients = item.Clients, DataItems = item.DataItems,
Params = item.Params, };
DataItems = item.DataItems, connect.Params.Prompt = "";
};
connect.Params.Prompt = "";
Connects.Add(connect); Connects.Add(connect);
// 加载时将 DataItems 同步到服务端内存数据表 // 加载时将 DataItems 同步到服务端内存数据表
ApplyAllDataToServer(connect); ApplyAllDataToServer(connect);
} }
break; break;
case ProtocolType.ModbusRtuClient: case ProtocolType.ModbusRtuClient:
{
var connect = new ModbusRtu.ModbusRtuClient
{ {
var connect = new ModbusRtu.ModbusRtuClient ID = item.ID,
{ Name = item.Name,
ID = item.ID, IP_SerialPort = item.IP_SerialPort,
Name = item.Name, Port = item.Port,
IP_SerialPort = item.IP_SerialPort, Type = item.Type,
Port = item.Port, Comment = item.Comment,
Type = item.Type, Params = item.Params,
Comment = item.Comment, DataItems = item.DataItems,
Params = item.Params, };
DataItems = item.DataItems, connect.Params.Prompt = "";
}; Connects.Add(connect);
connect.Params.Prompt = ""; }
Connects.Add(connect); break;
}
break;
case ProtocolType.FreeSerialProtocol: case ProtocolType.FreeSerialProtocol:
{
var connect = new SerialPort.FreeSerialProtocol
{ {
var connect = new SerialPort.FreeSerialProtocol ID = item.ID,
{ Name = item.Name,
ID = item.ID, IP_SerialPort = item.IP_SerialPort,
Name = item.Name, Port = item.Port,
IP_SerialPort = item.IP_SerialPort, Type = item.Type,
Port = item.Port, Comment = item.Comment,
Type = item.Type, Params = item.Params,
Comment = item.Comment, DataItems = item.DataItems,
Params = item.Params, };
DataItems = item.DataItems, connect.Params.Prompt = "";
}; Connects.Add(connect);
connect.Params.Prompt = ""; }
Connects.Add(connect); break;
}
break;
default: default:
SendErr("未配置的协议"); SendErr("未配置的协议");
break; break;
}
} }
} }

View File

@ -1,4 +1,4 @@
using PLCSharp.Core.Prism; using PLCSharp.Core.Prism;
using PLCSharp.Core.Tools; using PLCSharp.Core.Tools;
using PLCSharp.Models; using PLCSharp.Models;
using Prism.Commands; 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 ControllerSDK SDK;
private BackgroundWorker bkgWorker; private BackgroundWorker bkgWorker;
private string _IP; private string _IP;

View File

@ -1,4 +1,4 @@
using MiniExcelLibs; using MiniExcelLibs;
using PLCSharp.Core.Prism; using PLCSharp.Core.Prism;
using PLCSharp.Core.Tools; using PLCSharp.Core.Tools;
using PLCSharp.Models; 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<Axis> bind, Action<string> 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) internal void LoadRecipe(Guid CurrentRecipeID)
{ {
Stop(); Stop();

View File

@ -1,4 +1,4 @@
using PLCSharp.Core.Tools; using PLCSharp.Core.Tools;
using PLCSharp.VVMs.Connects.Socket; using PLCSharp.VVMs.Connects.Socket;
using System.Threading; using System.Threading;
@ -57,6 +57,9 @@ public class EpsonRobot : Robot
return r; return r;
} }
private volatile bool pollingStopped;
internal void EndPolling() => pollingStopped = true;
private void ConnectRobot() private void ConnectRobot()
{ {
// 启动状态轮询线程 // 启动状态轮询线程
@ -72,7 +75,7 @@ public class EpsonRobot : Robot
private void ReceivesRunState() private void ReceivesRunState()
{ {
while (true) while (!pollingStopped)
{ {
Thread.Sleep(1000); Thread.Sleep(1000);
try try
@ -165,7 +168,7 @@ public class EpsonRobot : Robot
private void ReceivesRemoteState() private void ReceivesRemoteState()
{ {
while (true) while (!pollingStopped)
try try
{ {
Status[13] = false; Status[13] = false;
@ -173,7 +176,7 @@ public class EpsonRobot : Robot
if (Status[14] && !ClientCommand.Connected) continue; if (Status[14] && !ClientCommand.Connected) continue;
ClientCommand.SendMsg("@ReturnHere,0\r\n"); ClientCommand.SendMsg("@ReturnHere,0\r\n");
Status[13] = true; Status[13] = true;
while (ClientCommand.Connected && Status[13]) while (!pollingStopped && ClientCommand.Connected && Status[13])
{ {
Thread.Sleep(10); Thread.Sleep(10);
try try

View File

@ -1,4 +1,4 @@
using PLCSharp.Core.Prism; using PLCSharp.Core.Prism;
using PLCSharp.Core.Tools; using PLCSharp.Core.Tools;
using PLCSharp.Models; using PLCSharp.Models;
using PLCSharp.VVMs.Robots.Epson; using PLCSharp.VVMs.Robots.Epson;
@ -88,29 +88,31 @@ namespace PLCSharp.VVMs.Robots
public void LoadRecipe(Guid CurrentRecipeID) 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(); if (item.RobotID == robot.ID && item.RecipeID == CurrentRecipeID)
foreach (var item in _DatasContext.RobotPoints)
{ {
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(); robot.RobotMatrices.Clear();
foreach (var item in _DatasContext.RobotMatrices) 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);
var matrix = item.DeepCopy(); robot.RobotMatrices.Add(matrix);
robot.Create(matrix);
robot.RobotMatrices.Add(matrix);
}
} }
} }
} }

View File

@ -234,6 +234,19 @@ namespace PLCSharp.VVMs.Vision
#region Camera #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 readonly HikCameras _HikCameras;
private ObservableCollection<CameraBase> _Cameras = []; private ObservableCollection<CameraBase> _Cameras = [];

View File

@ -9,7 +9,24 @@ public partial class ScriptReviewWindow : Window
private ScriptReviewWindow(ProjectChange change, string root) private ScriptReviewWindow(ProjectChange change, string root)
{ {
InitializeComponent(); 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<string>();
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" => "控件测量项", var subject = rename.Kind switch { "VisionLocalVariables" => "视觉局部变量", "ControlMeasurements" => "控件测量项",
"InterpolationSegments" => "插补段", "InterpolationPoints" => "插补段内点", "Recipes" => "配方", "SystemVariables" => "系统变量", "CustomControls" => "主页控件", "InterpolationSegments" => "插补段", "InterpolationPoints" => "插补段内点", "Recipes" => "配方", "SystemVariables" => "系统变量", "CustomControls" => "主页控件",