Persist portable PLCSharp project directories and configuration
This commit is contained in:
parent
12b51e0ca2
commit
b972271a14
@ -22,6 +22,7 @@ namespace PLCSharp
|
||||
/// </summary>
|
||||
public partial class App
|
||||
{
|
||||
internal bool SwitchingProject { get; set; }
|
||||
private Mutex mutex;
|
||||
|
||||
//第1执行
|
||||
@ -31,7 +32,14 @@ namespace PLCSharp
|
||||
/// <param name="containerRegistry">Prism 容器注册器</param>
|
||||
protected override void RegisterTypes(IContainerRegistry containerRegistry)
|
||||
{
|
||||
var args = Environment.GetCommandLineArgs().Skip(1).ToArray();
|
||||
bool switching = args.Length == 2 && args[0] == "--switch-project";
|
||||
mutex = new Mutex(true, "PLCSharp", out bool ret);
|
||||
if (!ret && switching)
|
||||
{
|
||||
try { ret = mutex.WaitOne(TimeSpan.FromSeconds(30)); }
|
||||
catch (AbandonedMutexException) { ret = true; }
|
||||
}
|
||||
|
||||
if (!ret)
|
||||
{
|
||||
@ -40,8 +48,20 @@ namespace PLCSharp
|
||||
}
|
||||
LoadConfig();
|
||||
//数据库
|
||||
_ = containerRegistry.RegisterSingleton<DatasContext>();
|
||||
_ = Container.Resolve<DatasContext>();
|
||||
ProjectDirectory project;
|
||||
try
|
||||
{
|
||||
project = args.Length == 2 && (switching || args[0] == "--project")
|
||||
? ProjectDirectory.Open(args[1]) : ProjectDirectory.New();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"无法打开工程:{ex.Message}", "PLCSharp");
|
||||
project = ProjectDirectory.New();
|
||||
}
|
||||
containerRegistry.RegisterInstance(project);
|
||||
containerRegistry.RegisterInstance(project.Data);
|
||||
containerRegistry.RegisterSingleton<MachineDataContext>();
|
||||
|
||||
RegisterEvents(); // 捕获全局异常
|
||||
|
||||
|
||||
@ -91,11 +91,6 @@ namespace PLCSharp.Models
|
||||
/// </summary>
|
||||
public DbSet<User> Users { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Recipes
|
||||
/// </summary>
|
||||
public DbSet<Recipe> Recipes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 系统全局变量集合
|
||||
/// </summary>
|
||||
@ -106,11 +101,6 @@ namespace PLCSharp.Models
|
||||
/// <summary>
|
||||
public DbSet<Variable> Variables { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Workflows
|
||||
/// </summary>
|
||||
public DbSet<Workflow> Workflows { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// VisionFunctions
|
||||
/// </summary>
|
||||
@ -220,20 +210,49 @@ namespace PLCSharp.Models
|
||||
? $"Data Source={DefaultDatabasePath}"
|
||||
: _connectionString);
|
||||
|
||||
private object _dbLock = new();
|
||||
internal readonly object Sync = new();
|
||||
internal Action<HashSet<string>> ConfigurationChanged;
|
||||
|
||||
internal static DatasContext CreateWorkingCopy() => new DatasContext(true);
|
||||
|
||||
private DatasContext(bool workingCopy)
|
||||
{
|
||||
_connectionString = "Data Source=:memory:";
|
||||
Database.OpenConnection();
|
||||
Database.EnsureCreated();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存
|
||||
/// </summary>
|
||||
public void Save()
|
||||
{
|
||||
lock (_dbLock)
|
||||
lock (Sync)
|
||||
{
|
||||
var tables = ConfigurationChanged == null ? null : ChangeTracker.Entries()
|
||||
.Where(e => e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted)
|
||||
.Select(e => e.Metadata.GetTableName()).ToHashSet();
|
||||
SaveChanges();
|
||||
if (tables != null) ConfigurationChanged(tables);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Accounts and logs belong to this installation. They never enter a project directory.
|
||||
public sealed class MachineDataContext : DatasContext
|
||||
{
|
||||
public MachineDataContext() { }
|
||||
internal MachineDataContext(string path) : base(path) { }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
base.OnModelCreating(builder);
|
||||
var projectTypes = builder.Model.GetEntityTypes().Select(entity => entity.ClrType)
|
||||
.Where(type => type != typeof(User) && type != typeof(ErrorLog)).ToList();
|
||||
foreach (var type in projectTypes) builder.Ignore(type);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SQLite 库的增量维护:补建缺失的表、补齐缺失的列。
|
||||
/// </summary>
|
||||
|
||||
@ -11,6 +11,8 @@ namespace PLCSharp.Models
|
||||
/// </summary>
|
||||
public partial class GlobalModel
|
||||
{
|
||||
private readonly MachineDataContext machineData;
|
||||
|
||||
#region 日志
|
||||
|
||||
private ObservableCollection<ErrorLog> _ErrorLogs = [];
|
||||
@ -49,7 +51,8 @@ namespace PLCSharp.Models
|
||||
var newLog = new ErrorLog(message.Content);
|
||||
TitleState.Info = message.Content;
|
||||
TitleState.Background = Brushes.Red;
|
||||
_DatasContext.ErrorLogs.Add(newLog);
|
||||
machineData.ErrorLogs.Add(newLog);
|
||||
machineData.Save();
|
||||
ShowLog();
|
||||
}
|
||||
|
||||
@ -59,7 +62,7 @@ namespace PLCSharp.Models
|
||||
{
|
||||
lock (loglock)
|
||||
{
|
||||
var showLog = _DatasContext.ErrorLogs.Where(e => e.Time.AddDays(1) >= DateTime.Now).OrderByDescending(l => l.Time).Take(30).ToList();
|
||||
var showLog = machineData.ErrorLogs.Where(e => e.Time.AddDays(1) >= DateTime.Now).OrderByDescending(l => l.Time).Take(30).ToList();
|
||||
|
||||
foreach (var item in showLog)
|
||||
{
|
||||
@ -95,6 +98,7 @@ namespace PLCSharp.Models
|
||||
if (err != null)
|
||||
{
|
||||
err.IsConfirm = true;
|
||||
machineData.Save();
|
||||
}
|
||||
}
|
||||
else if (r.Result == ButtonResult.No)
|
||||
|
||||
87
PLCSharpWpf/Models/GlobalModel.Project.cs
Normal file
87
PLCSharpWpf/Models/GlobalModel.Project.cs
Normal file
@ -0,0 +1,87 @@
|
||||
using Microsoft.Win32;
|
||||
using Prism.Commands;
|
||||
using System.Windows;
|
||||
|
||||
namespace PLCSharp.Models;
|
||||
|
||||
public partial class GlobalModel
|
||||
{
|
||||
internal ProjectDirectory Project { get; }
|
||||
public string ProjectLocation => Project.Root ?? "未保存工程";
|
||||
private AsyncDelegateCommand<string> projectManage;
|
||||
public AsyncDelegateCommand<string> ProjectManage => projectManage ??= new AsyncDelegateCommand<string>(ManageProjectAsync);
|
||||
|
||||
private static string ChooseFolder(string title)
|
||||
{
|
||||
var dialog = new OpenFolderDialog { Title = title };
|
||||
return dialog.ShowDialog() == true ? dialog.FolderName : null;
|
||||
}
|
||||
|
||||
internal bool SaveProject()
|
||||
{
|
||||
try
|
||||
{
|
||||
var root = Project.Root ?? ChooseFolder("选择空文件夹以保存工程");
|
||||
if (root == null) return false;
|
||||
Project.Save(root);
|
||||
RaisePropertyChanged(nameof(ProjectLocation));
|
||||
foreach (var recipe in Recipes)
|
||||
{
|
||||
recipe.Prompt = "";
|
||||
foreach (var flow in Project.Flows(recipe.ID))
|
||||
if (flow.Prompt == "已修改,请保存") flow.Prompt = "";
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendErrDialog($"工程保存失败:{ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ManageProjectAsync(string action)
|
||||
{
|
||||
if (WorkflowsModel.IsBusy || ModeState.State.Execute)
|
||||
{
|
||||
SendInfoDialog("请先停止运行并等待配方切换完成。");
|
||||
return;
|
||||
}
|
||||
if (action == "Save")
|
||||
{
|
||||
SaveProject();
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (Project.HasChanges)
|
||||
{
|
||||
var answer = MessageBox.Show("当前工程有未保存的修改。是否保存?", "切换工程",
|
||||
MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
|
||||
if (answer == MessageBoxResult.Cancel || (answer == MessageBoxResult.Yes && !SaveProject())) return;
|
||||
}
|
||||
var folder = ChooseFolder(action == "New" ? "选择空文件夹以新建工程" : "选择包含 project.json 的工程目录");
|
||||
if (folder == null) return;
|
||||
using var next = action == "New" ? ProjectDirectory.New() : ProjectDirectory.Open(folder);
|
||||
if (action == "New") next.Save(folder);
|
||||
// Hardware modules own pollers and vendor handles for their whole process lifetime.
|
||||
// Start the replacement session after this one has released its single-instance mutex.
|
||||
await WorkflowsModel.ChangeRecipeAsync(() =>
|
||||
{
|
||||
var start = new System.Diagnostics.ProcessStartInfo(Environment.ProcessPath) { UseShellExecute = false };
|
||||
if (string.Equals(System.IO.Path.GetFileNameWithoutExtension(Environment.ProcessPath), "dotnet", StringComparison.OrdinalIgnoreCase))
|
||||
start.ArgumentList.Add(typeof(App).Assembly.Location);
|
||||
start.ArgumentList.Add("--switch-project");
|
||||
start.ArgumentList.Add(next.Root);
|
||||
System.Diagnostics.Process.Start(start)?.Dispose();
|
||||
((App)Application.Current).SwitchingProject = true;
|
||||
Application.Current.Shutdown();
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendErrDialog($"工程操作失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -71,7 +71,7 @@ namespace PLCSharp.Models
|
||||
|
||||
private void ExecuteRecipeManage(string cmd)
|
||||
{
|
||||
if (WorkflowsModel?.IsChangingRecipe == true) return;
|
||||
if (WorkflowsModel?.IsBusy == true) return;
|
||||
if (ModeState.State.Execute)
|
||||
{
|
||||
SendInfoDialog($"无法在运行状态操作配方,请先停止");
|
||||
@ -84,43 +84,7 @@ namespace PLCSharp.Models
|
||||
break;
|
||||
|
||||
case "Save":
|
||||
var names = new List<string>();
|
||||
|
||||
foreach (var item in Recipes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(item.Name))
|
||||
{
|
||||
SendInfoDialog($"保存失败,名称{item.Name}不合适!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (names.Contains(item.Name))
|
||||
{
|
||||
SendInfoDialog($"保存失败,重复的名称{item.Name}!");
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
names.Add(item.Name);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var item in Recipes)
|
||||
{
|
||||
if (!_DatasContext.Recipes.Any(h => h.ID == item.ID))
|
||||
{
|
||||
_DatasContext.Recipes.Add(item);
|
||||
}
|
||||
else
|
||||
{
|
||||
var recipe = _DatasContext.Recipes.Where(c => c.ID == item.ID).FirstOrDefault();
|
||||
recipe.Name = item.Name;
|
||||
recipe.Comment = item.Comment;
|
||||
}
|
||||
}
|
||||
RecipeSelected.Prompt = "";
|
||||
_DatasContext.Save();
|
||||
|
||||
SaveProject();
|
||||
break;
|
||||
|
||||
case "Remove":
|
||||
@ -132,10 +96,21 @@ namespace PLCSharp.Models
|
||||
{
|
||||
var recipeId = RecipeSelected.ID;
|
||||
|
||||
var removed = RecipeSelected;
|
||||
var index = Recipes.IndexOf(removed);
|
||||
var previousDefault = Project.DefaultRecipeId;
|
||||
if (recipeId == previousDefault) Project.DefaultRecipeId = CurrentRecipe.ID;
|
||||
Recipes.RemoveAt(index);
|
||||
if (!SaveProject())
|
||||
{
|
||||
Project.DefaultRecipeId = previousDefault;
|
||||
Recipes.Insert(index, removed);
|
||||
RecipeSelected = removed;
|
||||
return;
|
||||
}
|
||||
// 级联删除配方关联的所有数据
|
||||
_DatasContext.Variables.RemoveRange(_DatasContext.Variables.Where(v => v.RecipeID == recipeId));
|
||||
_DatasContext.SystemVariables.RemoveRange(_DatasContext.SystemVariables.Where(v => v.RecipeID == recipeId));
|
||||
_DatasContext.Workflows.RemoveRange(_DatasContext.Workflows.Where(w => w.RecipeID == recipeId));
|
||||
_DatasContext.ImageDatas.RemoveRange(_DatasContext.ImageDatas.Where(i => i.RecipeID == recipeId));
|
||||
_DatasContext.AxisPoints.RemoveRange(_DatasContext.AxisPoints.Where(a => a.RecipeID == recipeId));
|
||||
_DatasContext.Matrices.RemoveRange(_DatasContext.Matrices.Where(m => m.RecipeID == recipeId));
|
||||
@ -149,14 +124,7 @@ namespace PLCSharp.Models
|
||||
_DatasContext.LocalImageDatas.RemoveRange(_DatasContext.LocalImageDatas.Where(l => visionFuncIds.Contains(l.FuncID)));
|
||||
_DatasContext.VisionFunctions.RemoveRange(_DatasContext.VisionFunctions.Where(v => v.RecipeID == recipeId));
|
||||
|
||||
var recipe = _DatasContext.Recipes.FirstOrDefault(r => r.ID == recipeId);
|
||||
if (recipe != null)
|
||||
{
|
||||
_DatasContext.Recipes.Remove(recipe);
|
||||
}
|
||||
|
||||
var name = RecipeSelected.Name;
|
||||
Recipes.Remove(RecipeSelected);
|
||||
var name = removed.Name;
|
||||
RecipeSelected = null;
|
||||
_DatasContext.Save();
|
||||
SendInfoDialog($"已删除配方:{name}");
|
||||
@ -171,7 +139,7 @@ namespace PLCSharp.Models
|
||||
case "Current":
|
||||
if (RecipeSelected != null)
|
||||
{
|
||||
if (CurrentRecipe.Name == RecipeSelected.Name) {
|
||||
if (CurrentRecipe.ID == RecipeSelected.ID) {
|
||||
|
||||
SendInfoDialog($"当前配方已经是:{CurrentRecipe.Name},不需要切换。");
|
||||
break;
|
||||
@ -179,11 +147,7 @@ namespace PLCSharp.Models
|
||||
|
||||
if (System.Windows.MessageBox.Show($"确认切换配方 [{RecipeSelected.Name}]?", "确认切换", MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes)
|
||||
break;
|
||||
var selectedId = RecipeSelected.ID;
|
||||
var current = _DatasContext.Recipes.FirstOrDefault(r => r.ID == selectedId);
|
||||
if (current == null) break;
|
||||
|
||||
_ = ReloadRecipeAsync(current);
|
||||
_ = ReloadRecipeAsync(RecipeSelected);
|
||||
}
|
||||
|
||||
break;
|
||||
@ -223,8 +187,7 @@ namespace PLCSharp.Models
|
||||
}).ToList();
|
||||
|
||||
// 工艺流程
|
||||
sheets["工艺流程"] = _DatasContext.Workflows
|
||||
.Where(w => w.RecipeID == recipeId)
|
||||
sheets["工艺流程"] = Project.Flows(recipeId)
|
||||
.Select(w => new
|
||||
{
|
||||
ID = w.ID.ToString(),
|
||||
@ -467,13 +430,13 @@ namespace PLCSharp.Models
|
||||
var idStr = (string)row.ID;
|
||||
if (string.IsNullOrWhiteSpace(idStr)) continue;
|
||||
if (!Guid.TryParse(idStr, out var id)) continue;
|
||||
if (_DatasContext.Workflows.Any(w => w.ID == id)) continue;
|
||||
if (Recipes.SelectMany(r => Project.Flows(r.ID)).Any(w => w.ID == id)) continue;
|
||||
|
||||
var name = (string)row.Name;
|
||||
if (string.IsNullOrWhiteSpace(name)) continue;
|
||||
if (_DatasContext.Workflows.Any(w => w.Name == name && w.RecipeID == recipeId)) continue;
|
||||
if (Project.Flows(recipeId).Any(w => w.Name == name)) continue;
|
||||
|
||||
_DatasContext.Workflows.Add(new Workflow
|
||||
Project.Flows(recipeId).Add(new Workflow
|
||||
{
|
||||
ID = id,
|
||||
RecipeID = recipeId,
|
||||
@ -776,6 +739,7 @@ namespace PLCSharp.Models
|
||||
_DatasContext.CustomControls.Add(cc);
|
||||
}
|
||||
|
||||
if (!SaveProject()) return;
|
||||
_DatasContext.Save();
|
||||
SendInfoDialog($"配方 [{RecipeSelected.Name}] 数据已导入,请切换配方刷新");
|
||||
}
|
||||
@ -800,9 +764,6 @@ namespace PLCSharp.Models
|
||||
{
|
||||
if (selected != null)
|
||||
{
|
||||
foreach (var item in _DatasContext.Recipes)
|
||||
item.Current = item.ID == selected.ID;
|
||||
_DatasContext.Save();
|
||||
foreach (var item in Recipes)
|
||||
item.Current = item.ID == selected.ID;
|
||||
CurrentRecipe = selected;
|
||||
@ -855,16 +816,11 @@ namespace PLCSharp.Models
|
||||
RobotModel.LoadRecipe(CurrentRecipe.ID);
|
||||
|
||||
//加载当前配方的任务列表
|
||||
WorkflowsModel.Workflows.Clear();
|
||||
var currRecipeWorkflows = _DatasContext.Workflows.Where(c => c.RecipeID == CurrentRecipe.ID);
|
||||
foreach (var item in currRecipeWorkflows)
|
||||
{
|
||||
var itemcopy = item.DeepCopy();
|
||||
itemcopy.Prompt = "";
|
||||
WorkflowsModel.Workflows.Add(itemcopy);
|
||||
itemcopy.Compile.Execute();
|
||||
itemcopy.Start(this);
|
||||
}
|
||||
WorkflowsModel.SelectedTask = null;
|
||||
WorkflowsModel.Workflows = Project.Flows(CurrentRecipe.ID);
|
||||
// Source from a newly opened directory is compiled only by the editor’s Compile command.
|
||||
foreach (var workflow in WorkflowsModel.Workflows)
|
||||
workflow.Start(this);
|
||||
}
|
||||
|
||||
private void RecipeCopy()
|
||||
@ -993,21 +949,18 @@ namespace PLCSharp.Models
|
||||
|
||||
// 任务列表
|
||||
|
||||
var workflows = _DatasContext.Workflows.Where(c => c.RecipeID == RecipeSelected.ID);
|
||||
foreach (var item in workflows)
|
||||
foreach (var item in Project.Flows(RecipeSelected.ID))
|
||||
{
|
||||
if (item != null)
|
||||
{
|
||||
var itemCopy = item.DeepCopy();
|
||||
itemCopy.RecipeID = newRecipe.ID;
|
||||
itemCopy.ID = Guid.NewGuid();
|
||||
_DatasContext.Workflows.Add(itemCopy);
|
||||
}
|
||||
var copy = new Workflow { RecipeID = newRecipe.ID, Name = item.Name,
|
||||
Comment = item.Comment, AutomaticExecution = item.AutomaticExecution,
|
||||
CycleDelayTime = item.CycleDelayTime };
|
||||
copy.Code = item.Code?.Replace($"Extension_{item.ID:N}", $"Extension_{copy.ID:N}");
|
||||
Project.Flows(newRecipe.ID).Add(copy);
|
||||
}
|
||||
|
||||
_DatasContext.Recipes.Add(newRecipe);
|
||||
try
|
||||
{
|
||||
if (!SaveProject()) return;
|
||||
_DatasContext.Save();
|
||||
SendInfoDialog($"配方 [{newRecipe.Name}] 复制成功");
|
||||
}
|
||||
|
||||
@ -38,38 +38,10 @@ namespace PLCSharp.Models
|
||||
//注册域构造器
|
||||
.Preheating<NatashaDomainCreator>();
|
||||
|
||||
foreach (var item in _DatasContext.Recipes)
|
||||
{
|
||||
Recipes.Add(item.DeepCopy());
|
||||
}
|
||||
|
||||
if (Recipes.Count == 0)
|
||||
{
|
||||
var recipe = new Recipe
|
||||
{
|
||||
Name = "First",
|
||||
Comment = "",
|
||||
Prompt = "默认配方",
|
||||
Current = true
|
||||
};
|
||||
Recipes.Add(recipe);
|
||||
RecipeSelected = recipe;
|
||||
ExecuteRecipeManage("Save");
|
||||
CurrentRecipe = recipe;
|
||||
}
|
||||
else
|
||||
{
|
||||
CurrentRecipe = Recipes.Where(r => r.Current).FirstOrDefault();
|
||||
|
||||
if (CurrentRecipe == null)
|
||||
{
|
||||
CurrentRecipe = Recipes.FirstOrDefault();
|
||||
CurrentRecipe.Current = true;
|
||||
RecipeSelected = CurrentRecipe;
|
||||
ExecuteRecipeManage("Save");
|
||||
}
|
||||
RecipeSelected ??= CurrentRecipe;
|
||||
}
|
||||
Project = container.Resolve<ProjectDirectory>();
|
||||
machineData = container.Resolve<MachineDataContext>();
|
||||
Recipes = Project.Recipes;
|
||||
CurrentRecipe = RecipeSelected = Recipes.Single(r => r.ID == Project.DefaultRecipeId);
|
||||
|
||||
VariablesModel = container.Resolve<VariablesModel>();
|
||||
VariablesModel.Init(this);
|
||||
@ -80,6 +52,8 @@ namespace PLCSharp.Models
|
||||
ControllersModel.Init(this);
|
||||
|
||||
WorkflowsModel = container.Resolve<WorkflowsModel>();
|
||||
WorkflowsModel.Init(this);
|
||||
WorkflowsModel.Workflows = Project.Flows(CurrentRecipe.ID);
|
||||
|
||||
VisionsModel = container.Resolve<VisionsModel>();
|
||||
|
||||
|
||||
127
PLCSharpWpf/Models/ProjectConfiguration.cs
Normal file
127
PLCSharpWpf/Models/ProjectConfiguration.cs
Normal file
@ -0,0 +1,127 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using PLCSharp.VVMs.Vision;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace PLCSharp.Models;
|
||||
|
||||
// The editor keeps using its EF queries against a private in-memory working copy.
|
||||
// Only the explicitly listed configuration tables are part of the project format.
|
||||
internal static class ProjectConfiguration
|
||||
{
|
||||
internal static readonly IReadOnlyDictionary<string, string[]> Groups = new Dictionary<string, string[]>
|
||||
{
|
||||
["hardware"] = ["Controllers", "Axes", "DI", "DQ", "Connects", "Robots", "Cylinders", "Cameras"],
|
||||
["variables"] = ["Variables", "SystemVariables"],
|
||||
["points"] = ["AxisPoints", "Matrices", "InterpolationGroups", "RobotPoints", "RobotMatrices"],
|
||||
["vision"] = ["VisionFunctions", "ImageDatas", "LocalImageDatas"],
|
||||
["interface"] = ["CanvasConfigs", "CustomControls"]
|
||||
};
|
||||
|
||||
private static IEntityType Entity(DatasContext db, string table) =>
|
||||
db.Model.GetEntityTypes().Single(e => e.GetTableName() == table);
|
||||
|
||||
private static string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"") + "\"";
|
||||
|
||||
internal static JsonObject Capture(DatasContext db, string[] tables)
|
||||
{
|
||||
var document = new JsonObject();
|
||||
foreach (var table in tables)
|
||||
{
|
||||
var entity = Entity(db, table);
|
||||
var fields = entity.GetProperties().ToArray();
|
||||
using var query = db.Database.GetDbConnection().CreateCommand();
|
||||
var columns = string.Join(", ", fields.Select(p => Quote(p.GetColumnName())));
|
||||
query.CommandText = $"SELECT {columns} FROM {Quote(table)} ORDER BY {Quote(entity.FindPrimaryKey().Properties.Single().GetColumnName())}";
|
||||
using var reader = query.ExecuteReader();
|
||||
var rows = new JsonArray();
|
||||
while (reader.Read())
|
||||
{
|
||||
var row = new JsonObject();
|
||||
for (int i = 0; i < fields.Length; i++)
|
||||
{
|
||||
var p = fields[i];
|
||||
JsonNode value = null;
|
||||
if (!reader.IsDBNull(i))
|
||||
{
|
||||
var raw = reader.GetValue(i);
|
||||
value = IsJson(p) ? (JsonNode.Parse((string)raw) ?? JsonValue.Create("null")) : JsonSerializer.SerializeToNode(raw);
|
||||
if (table == "VisionFunctions" && p.GetColumnName() == "VisionFlows")
|
||||
EmbedImageInputs(value);
|
||||
}
|
||||
row.Add(p.GetColumnName(), value);
|
||||
}
|
||||
rows.Add(row);
|
||||
}
|
||||
document.Add(table, rows);
|
||||
}
|
||||
return document;
|
||||
}
|
||||
|
||||
private static bool IsJson(IProperty property) => property.ClrType == typeof(string)
|
||||
&& property.Name.StartsWith("Serialized", StringComparison.Ordinal);
|
||||
|
||||
private static void EmbedImageInputs(JsonNode flows)
|
||||
{
|
||||
foreach (var flow in flows.AsArray())
|
||||
{
|
||||
if ((int?)flow["Type"] != (int)VisionFlowType.从文件获取图片 ||
|
||||
flow["StringParams"] is not JsonObject args || args["Path"] is not JsonValue path) continue;
|
||||
if (args["ImageBase64"] == null)
|
||||
args["ImageBase64"] = Convert.ToBase64String(File.ReadAllBytes(path.GetValue<string>()));
|
||||
args["Path"] = Path.GetFileName(path.GetValue<string>());
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Restore(DatasContext db, string[] tables, JsonObject document)
|
||||
{
|
||||
foreach (var table in tables)
|
||||
{
|
||||
var entity = Entity(db, table);
|
||||
var fields = entity.GetProperties().ToArray();
|
||||
if (document[table] is not JsonArray rows)
|
||||
throw new InvalidDataException($"工程配置缺少 {table}。");
|
||||
using var insert = db.Database.GetDbConnection().CreateCommand();
|
||||
var columns = string.Join(", ", fields.Select(p => Quote(p.GetColumnName())));
|
||||
var parameters = fields.Select((p, i) => "$p" + i).ToArray();
|
||||
insert.CommandText = $"INSERT INTO {Quote(table)} ({columns}) VALUES ({string.Join(", ", parameters)})";
|
||||
foreach (var name in parameters)
|
||||
{
|
||||
var parameter = insert.CreateParameter();
|
||||
parameter.ParameterName = name;
|
||||
insert.Parameters.Add(parameter);
|
||||
}
|
||||
foreach (var item in rows)
|
||||
{
|
||||
var row = item.AsObject();
|
||||
for (int i = 0; i < fields.Length; i++)
|
||||
{
|
||||
var p = fields[i];
|
||||
if (!row.TryGetPropertyValue(p.GetColumnName(), out var value))
|
||||
throw new InvalidDataException($"{table} 缺少字段 {p.GetColumnName()}。");
|
||||
object raw = DBNull.Value;
|
||||
if (value != null)
|
||||
{
|
||||
if (IsJson(p)) raw = value.GetValueKind() == JsonValueKind.String && (string)value == "null" ? "null" : value.ToJsonString();
|
||||
else if (p.ClrType == typeof(byte[])) raw = Convert.FromBase64String((string)value);
|
||||
else raw = value.GetValueKind() switch
|
||||
{
|
||||
JsonValueKind.String => (string)value,
|
||||
JsonValueKind.Number when value.AsValue().TryGetValue<long>(out var n) => n,
|
||||
JsonValueKind.Number => (double)value,
|
||||
_ => throw new InvalidDataException($"{table}.{p.Name} 类型无效。")
|
||||
};
|
||||
// SQLite stores EF GUID keys in upper-case text.
|
||||
if (p.ClrType == typeof(Guid)) raw = Guid.Parse((string)raw).ToString("D").ToUpperInvariant();
|
||||
}
|
||||
insert.Parameters[i].Value = raw;
|
||||
}
|
||||
insert.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
267
PLCSharpWpf/Models/ProjectDirectory.cs
Normal file
267
PLCSharpWpf/Models/ProjectDirectory.cs
Normal file
@ -0,0 +1,267 @@
|
||||
using PLCSharp.VVMs.Recipe;
|
||||
using PLCSharp.VVMs.Workflows;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace PLCSharp.Models;
|
||||
|
||||
public sealed class ProjectDirectory : IDisposable
|
||||
{
|
||||
private sealed record Manifest(int FormatVersion, Guid ProjectId, Guid DefaultRecipeId, Guid[] Recipes);
|
||||
private sealed record RecipeFile(Guid Id, string Name, string Comment, FlowFile[] Workflows);
|
||||
private sealed record FlowFile(Guid Id, string Name, string Comment, bool AutomaticExecution, double CycleDelayTime);
|
||||
|
||||
private static readonly JsonSerializerOptions Json = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
public DatasContext Data { get; } = DatasContext.CreateWorkingCopy();
|
||||
private readonly Dictionary<string, string> configuration = new();
|
||||
private readonly HashSet<string> pendingGroups = new();
|
||||
private static string ConfigPath(string group) => $"configuration/{group}.json";
|
||||
|
||||
private ProjectDirectory()
|
||||
{
|
||||
Data.ConfigurationChanged = PersistConfiguration;
|
||||
}
|
||||
|
||||
private void Capture(string group)
|
||||
{
|
||||
configuration[ConfigPath(group)] = Serialize(ProjectConfiguration.Capture(Data, ProjectConfiguration.Groups[group]));
|
||||
}
|
||||
|
||||
private void PersistConfiguration(HashSet<string> tables)
|
||||
{
|
||||
foreach (var (group, members) in ProjectConfiguration.Groups)
|
||||
if (members.Any(tables.Contains)) pendingGroups.Add(group);
|
||||
if (pendingGroups.Count == 0) return;
|
||||
foreach (var group in pendingGroups) Capture(group);
|
||||
if (Root != null)
|
||||
{
|
||||
var files = new Dictionary<string, string>(baseline);
|
||||
foreach (var group in pendingGroups) files[ConfigPath(group)] = configuration[ConfigPath(group)];
|
||||
WriteFiles(Root, files, pendingGroups.Select(ConfigPath).ToArray());
|
||||
}
|
||||
pendingGroups.Clear();
|
||||
}
|
||||
|
||||
public void Dispose() => Data.Dispose();
|
||||
|
||||
private Dictionary<string, string> baseline = new();
|
||||
private readonly Dictionary<Guid, ObservableCollection<Workflow>> workflows = new();
|
||||
public ObservableCollection<Recipe> Recipes { get; } = new();
|
||||
public string Root { get; private set; }
|
||||
public Guid Id { get; private set; } = Guid.NewGuid();
|
||||
public Guid DefaultRecipeId { get; set; }
|
||||
|
||||
public ObservableCollection<Workflow> Flows(Guid recipeId)
|
||||
{
|
||||
if (!workflows.TryGetValue(recipeId, out var items))
|
||||
workflows.Add(recipeId, items = new());
|
||||
return items;
|
||||
}
|
||||
|
||||
public static ProjectDirectory New()
|
||||
{
|
||||
var project = new ProjectDirectory();
|
||||
var recipe = new Recipe { Name = "First", Comment = "", Prompt = "", Current = true };
|
||||
project.Recipes.Add(recipe);
|
||||
project.DefaultRecipeId = recipe.ID;
|
||||
foreach (var group in ProjectConfiguration.Groups.Keys) project.Capture(group);
|
||||
project.baseline = project.Files();
|
||||
return project;
|
||||
}
|
||||
|
||||
private static string RecipePath(Guid id) => $"recipes/{id:D}/recipe.json";
|
||||
private static string ScriptPath(Guid recipe, Guid flow) => $"recipes/{recipe:D}/workflows/{flow:D}.cs";
|
||||
private static string Serialize<T>(T value) => JsonSerializer.Serialize(value, Json) + "\n";
|
||||
|
||||
public static ProjectDirectory Open(string directory)
|
||||
{
|
||||
var project = new ProjectDirectory { Root = Path.GetFullPath(directory) };
|
||||
try
|
||||
{
|
||||
project.ReadDirectory();
|
||||
return project;
|
||||
}
|
||||
catch
|
||||
{
|
||||
project.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void ReadDirectory()
|
||||
{
|
||||
string Read(string path)
|
||||
{
|
||||
string value = File.ReadAllText(Path.Combine(Root, path));
|
||||
baseline.Add(path, value);
|
||||
return value;
|
||||
}
|
||||
var manifest = JsonSerializer.Deserialize<Manifest>(Read("project.json"), Json);
|
||||
if (manifest?.FormatVersion != 2 || manifest.ProjectId == Guid.Empty || manifest.Recipes == null)
|
||||
throw new InvalidDataException("工程清单无效或版本不受支持。");
|
||||
Id = manifest.ProjectId;
|
||||
DefaultRecipeId = manifest.DefaultRecipeId;
|
||||
foreach (var id in manifest.Recipes)
|
||||
{
|
||||
var data = JsonSerializer.Deserialize<RecipeFile>(Read(RecipePath(id)), Json);
|
||||
if (data == null || data.Id != id || data.Workflows == null)
|
||||
throw new InvalidDataException($"配方文件无效:{id}");
|
||||
Recipes.Add(new Recipe { ID = id, Name = data.Name, Comment = data.Comment,
|
||||
Current = id == DefaultRecipeId, Prompt = "" });
|
||||
foreach (var flow in data.Workflows)
|
||||
{
|
||||
Flows(id).Add(new Workflow { ID = flow.Id, RecipeID = id, Name = flow.Name,
|
||||
Comment = flow.Comment, AutomaticExecution = flow.AutomaticExecution,
|
||||
CycleDelayTime = flow.CycleDelayTime, Code = Read(ScriptPath(id, flow.Id)), Prompt = "" });
|
||||
}
|
||||
}
|
||||
foreach (var (group, tables) in ProjectConfiguration.Groups)
|
||||
{
|
||||
var path = ConfigPath(group);
|
||||
var json = Read(path);
|
||||
ProjectConfiguration.Restore(Data, tables, System.Text.Json.Nodes.JsonNode.Parse(json).AsObject());
|
||||
configuration.Add(path, json);
|
||||
}
|
||||
Validate();
|
||||
}
|
||||
|
||||
private void Validate()
|
||||
{
|
||||
if (!Recipes.Any(r => r.ID == DefaultRecipeId))
|
||||
throw new InvalidDataException("工程缺少默认配方。");
|
||||
var ids = new HashSet<Guid>();
|
||||
void Check(Guid id, string name, HashSet<string> names)
|
||||
{
|
||||
if (id == Guid.Empty || !ids.Add(id) || string.IsNullOrWhiteSpace(name) || !names.Add(name))
|
||||
throw new InvalidDataException($"名称为空、名称重复或标识重复:{name}");
|
||||
}
|
||||
var recipes = new HashSet<string>();
|
||||
foreach (var recipe in Recipes)
|
||||
{
|
||||
Check(recipe.ID, recipe.Name, recipes);
|
||||
var names = new HashSet<string>();
|
||||
foreach (var flow in Flows(recipe.ID))
|
||||
Check(flow.ID, flow.Name, names);
|
||||
}
|
||||
}
|
||||
|
||||
private Dictionary<string, string> Files()
|
||||
{
|
||||
var files = new Dictionary<string, string>(configuration);
|
||||
foreach (var recipe in Recipes)
|
||||
{
|
||||
var flows = Flows(recipe.ID);
|
||||
foreach (var flow in flows)
|
||||
files.Add(ScriptPath(recipe.ID, flow.ID), flow.Code ?? "");
|
||||
files.Add(RecipePath(recipe.ID), Serialize(new RecipeFile(recipe.ID, recipe.Name, recipe.Comment,
|
||||
flows.Select(f => new FlowFile(f.ID, f.Name, f.Comment, f.AutomaticExecution, f.CycleDelayTime)).ToArray())));
|
||||
}
|
||||
files.Add("project.json", Serialize(new Manifest(2, Id, DefaultRecipeId, Recipes.Select(r => r.ID).ToArray())));
|
||||
return files;
|
||||
}
|
||||
|
||||
public bool HasChanges
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (Data.Sync)
|
||||
return pendingGroups.Count > 0 || Data.ChangeTracker.HasChanges()
|
||||
|| !Files().OrderBy(p => p.Key).SequenceEqual(baseline.OrderBy(p => p.Key));
|
||||
}
|
||||
}
|
||||
|
||||
public void Save(string newDirectory = null)
|
||||
{
|
||||
lock (Data.Sync)
|
||||
{
|
||||
Validate();
|
||||
Data.SaveChanges();
|
||||
foreach (var group in ProjectConfiguration.Groups.Keys) Capture(group);
|
||||
SaveAll(newDirectory);
|
||||
pendingGroups.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveAll(string newDirectory)
|
||||
{
|
||||
var root = Root ?? Path.GetFullPath(newDirectory ?? throw new InvalidOperationException("请选择工程目录。"));
|
||||
WriteFiles(root, Files());
|
||||
}
|
||||
|
||||
private void WriteFiles(string root, Dictionary<string, string> files, string[] scope = null)
|
||||
{
|
||||
Directory.CreateDirectory(root);
|
||||
// Serialize writers and detect edits made after this instance opened the project.
|
||||
using var gate = new FileStream(Path.Combine(root, ".plcsharp-save.lock"), FileMode.CreateNew,
|
||||
FileAccess.Write, FileShare.None, 1, FileOptions.DeleteOnClose);
|
||||
if (Root == null && Directory.EnumerateFileSystemEntries(root).Any(p => Path.GetFileName(p) != ".plcsharp-save.lock"))
|
||||
throw new IOException("新建工程需要一个空目录。");
|
||||
var previous = Root == null ? new Dictionary<string, string>() : baseline;
|
||||
var paths = scope ?? files.Keys.Union(previous.Keys).ToArray();
|
||||
foreach (var path in paths)
|
||||
{
|
||||
var full = Path.Combine(root, path);
|
||||
var disk = File.Exists(full) ? File.ReadAllText(full) : null;
|
||||
previous.TryGetValue(path, out var original);
|
||||
if (disk != original)
|
||||
throw new IOException($"文件已在外部修改,请重新打开工程:{path}");
|
||||
}
|
||||
|
||||
// Stage all writes before replacing files. Keep originals until every change succeeds.
|
||||
var stage = Directory.CreateDirectory(Path.Combine(root, ".save-" + Guid.NewGuid().ToString("N"))).FullName;
|
||||
var backups = new List<(string Target, string Original)>();
|
||||
var installed = new List<string>();
|
||||
bool keepBackups = false;
|
||||
try
|
||||
{
|
||||
foreach (var path in paths)
|
||||
{
|
||||
if (!files.TryGetValue(path, out var value)) continue;
|
||||
if (previous.TryGetValue(path, out var old) && old == value) continue;
|
||||
var temp = Path.Combine(stage, path);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(temp));
|
||||
File.WriteAllText(temp, value);
|
||||
}
|
||||
foreach (var path in paths)
|
||||
{
|
||||
var temp = Path.Combine(stage, path);
|
||||
if (files.ContainsKey(path) && !File.Exists(temp)) continue;
|
||||
var target = Path.Combine(root, path);
|
||||
if (previous.ContainsKey(path))
|
||||
{
|
||||
var backup = Path.Combine(stage, Guid.NewGuid().ToString());
|
||||
File.Move(target, backup);
|
||||
backups.Add((target, backup));
|
||||
}
|
||||
if (files.ContainsKey(path))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target));
|
||||
File.Move(temp, target);
|
||||
installed.Add(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
keepBackups = true;
|
||||
foreach (var path in installed) File.Delete(path);
|
||||
foreach (var (target, original) in backups) File.Move(original, target);
|
||||
keepBackups = false;
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!keepBackups) Directory.Delete(stage, true);
|
||||
}
|
||||
Root = root;
|
||||
baseline = files;
|
||||
}
|
||||
}
|
||||
|
||||
@ -21,6 +21,7 @@ namespace PLCSharp.VVMs.Authority
|
||||
/// </summary>
|
||||
public LoginModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService)
|
||||
{
|
||||
_DatasContext = container.Resolve<PLCSharp.Models.MachineDataContext>();
|
||||
//已注册用户
|
||||
var users = _DatasContext.Users?.ToList();
|
||||
|
||||
|
||||
@ -122,8 +122,21 @@ namespace PLCSharp.VVMs.GlobalVariables
|
||||
[Column(TypeName = "INTEGER")]
|
||||
public bool RetainPersistent { get; set; }
|
||||
|
||||
internal void RestoreValue(DatasContext context)
|
||||
{
|
||||
_DatasContext = context;
|
||||
// Hydration is a read. Retained values must not trigger a project save while opening it.
|
||||
var initial = DynamicValue(DefaultValueStr, Type);
|
||||
_DefaultValue = IsValidValue(initial, Type) ? initial : null;
|
||||
var saved = RetainPersistent ? DynamicValue(ValueStr, Type) : _DefaultValue;
|
||||
_Value = IsValidValue(saved, Type) ? saved : null;
|
||||
RaisePropertyChanged(nameof(Value));
|
||||
RaisePropertyChanged(nameof(DefaultValue));
|
||||
}
|
||||
|
||||
private static bool IsValidValue(dynamic value, VariableDataType type)
|
||||
{
|
||||
if (value is null) return false;
|
||||
return type switch
|
||||
{
|
||||
VariableDataType.Int32 => int.TryParse(value.ToString(), out int _),
|
||||
@ -286,8 +299,21 @@ namespace PLCSharp.VVMs.GlobalVariables
|
||||
[Column(TypeName = "INTEGER")]
|
||||
public bool RetainPersistent { get; set; }
|
||||
|
||||
internal void RestoreValue(DatasContext context)
|
||||
{
|
||||
_DatasContext = context;
|
||||
// Hydration is a read. Retained values must not trigger a project save while opening it.
|
||||
var initial = DynamicValue(DefaultValueStr, Type);
|
||||
_DefaultValue = IsValidValue(initial, Type) ? initial : null;
|
||||
var saved = RetainPersistent ? DynamicValue(ValueStr, Type) : _DefaultValue;
|
||||
_Value = IsValidValue(saved, Type) ? saved : null;
|
||||
RaisePropertyChanged(nameof(Value));
|
||||
RaisePropertyChanged(nameof(DefaultValue));
|
||||
}
|
||||
|
||||
private static bool IsValidValue(dynamic value, VariableDataType type)
|
||||
{
|
||||
if (value is null) return false;
|
||||
return type switch
|
||||
{
|
||||
VariableDataType.Int32 => int.TryParse(value.ToString(), out int _),
|
||||
|
||||
@ -51,16 +51,7 @@ namespace PLCSharp.VVMs.GlobalVariables
|
||||
var variables = _DatasContext.Variables.Where(c => c.RecipeID == CurrentRecipeID);
|
||||
foreach (var item in variables)
|
||||
{
|
||||
item._DatasContext = _DatasContext;
|
||||
if (item.RetainPersistent)
|
||||
{
|
||||
item.Value = Variable.DynamicValue(item.ValueStr, item.Type);
|
||||
}
|
||||
else
|
||||
{
|
||||
item.Value = Variable.DynamicValue(item.DefaultValueStr, item.Type);
|
||||
item.DefaultValue = item.Value;
|
||||
}
|
||||
item.RestoreValue(_DatasContext);
|
||||
Variables.Add(item);
|
||||
}
|
||||
|
||||
@ -69,16 +60,7 @@ namespace PLCSharp.VVMs.GlobalVariables
|
||||
var systemVariables = _DatasContext.SystemVariables.Where(c => c.RecipeID == CurrentRecipeID);
|
||||
foreach (var item in systemVariables)
|
||||
{
|
||||
item._DatasContext = _DatasContext;
|
||||
if (item.RetainPersistent)
|
||||
{
|
||||
item.Value = Variable.DynamicValue(item.ValueStr, item.Type);
|
||||
}
|
||||
else
|
||||
{
|
||||
item.Value = Variable.DynamicValue(item.DefaultValueStr, item.Type);
|
||||
item.DefaultValue = item.Value;
|
||||
}
|
||||
item.RestoreValue(_DatasContext);
|
||||
SystemVariables.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
@ -58,6 +58,7 @@ namespace PLCSharp.VVMs.MainWindow
|
||||
|
||||
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
|
||||
{
|
||||
if (((App)Application.Current).SwitchingProject) return;
|
||||
var vm = this.DataContext as MainWindowViewModel;
|
||||
vm?.Exit.Execute();
|
||||
e.Cancel = true;
|
||||
|
||||
@ -66,5 +66,11 @@
|
||||
</DataGrid>
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
<StackPanel Grid.Row="1" Orientation="Horizontal">
|
||||
<Button Command="{Binding Model.ProjectManage}" CommandParameter="New" Content="新建工程…" Margin="3,0" />
|
||||
<Button Command="{Binding Model.ProjectManage}" CommandParameter="Open" Content="打开工程…" Margin="3,0" />
|
||||
<Button Command="{Binding Model.ProjectManage}" CommandParameter="Save" Content="保存工程" Margin="3,0" />
|
||||
<TextBlock Text="{Binding Model.ProjectLocation}" VerticalAlignment="Center" Margin="8,0" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@ -21,6 +21,7 @@ namespace PLCSharp.VVMs.Vision.Camera
|
||||
try
|
||||
{
|
||||
SDKSystem.Initialize();
|
||||
sdkInitialized = true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
@ -35,9 +36,11 @@ namespace PLCSharp.VVMs.Vision.Camera
|
||||
/// <param name="e">e</param>
|
||||
protected override void OnExit(object sender, EventArgs e)
|
||||
{
|
||||
SDKSystem.Finalize();
|
||||
if (sdkInitialized) SDKSystem.Finalize();
|
||||
}
|
||||
|
||||
private readonly bool sdkInitialized;
|
||||
|
||||
private readonly DeviceTLayerType enumTLayerType = DeviceTLayerType.MvGigEDevice
|
||||
| DeviceTLayerType.MvUsbDevice;
|
||||
|
||||
|
||||
@ -42,7 +42,8 @@ public partial class VisionConfigViewModel
|
||||
SelectedVisionFunction.Src = Cv2.ImRead(ofd.FileName);
|
||||
if (SelectedVisionFunction.Src != null && !SelectedVisionFunction.Src.Empty())
|
||||
{
|
||||
SelectVisionFlow.StringParams["Path"] = ofd.FileName;
|
||||
SelectVisionFlow.StringParams["ImageBase64"] = Convert.ToBase64String(System.IO.File.ReadAllBytes(ofd.FileName));
|
||||
SelectVisionFlow.StringParams["Path"] = System.IO.Path.GetFileName(ofd.FileName);
|
||||
|
||||
ShowMat = SelectedVisionFunction.Src;
|
||||
}
|
||||
|
||||
@ -21,6 +21,11 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Access
|
||||
/// <returns>返回布尔值</returns>
|
||||
public bool Execute(VisionFunction func, VisionFlow item)
|
||||
{
|
||||
if (item.StringParams.TryGetValue("ImageBase64", out var embedded))
|
||||
{
|
||||
func.Src = Cv2.ImDecode(Convert.FromBase64String(embedded), ImreadModes.Color);
|
||||
return !func.Src.Empty();
|
||||
}
|
||||
if (item.StringParams.TryGetValue("Path", out string filePath))
|
||||
{
|
||||
if (File.Exists(filePath))
|
||||
|
||||
@ -52,8 +52,7 @@ namespace PLCSharp.VVMs.Workflows
|
||||
SelectedFlowTask.CompiledTime = DateTime.Now;
|
||||
SelectedFlowTask.Flow.Step = 0;
|
||||
await CustomTextEditor.FormatCodeAsync();
|
||||
GlobalModel.WorkflowsModel.Manage.Execute("Save");
|
||||
SelectedFlowTask.Compile.Execute();
|
||||
if (GlobalModel.SaveProject()) SelectedFlowTask.Compile.Execute();
|
||||
}
|
||||
|
||||
private Workflow _SelectedFlowTask;
|
||||
|
||||
@ -70,10 +70,11 @@ namespace PLCSharp.VVMs.Workflows
|
||||
_Manage ??= new DelegateCommand<string>(ExecuteManage);
|
||||
|
||||
internal bool IsChangingRecipe { get; private set; }
|
||||
internal bool IsBusy => IsChangingRecipe || _removingTask;
|
||||
|
||||
internal async Task ChangeRecipeAsync(Action loadRecipe)
|
||||
{
|
||||
if (IsChangingRecipe) return;
|
||||
if (IsBusy) return;
|
||||
IsChangingRecipe = true;
|
||||
try
|
||||
{
|
||||
@ -88,11 +89,11 @@ namespace PLCSharp.VVMs.Workflows
|
||||
|
||||
private void ExecuteManage(string cmd)
|
||||
{
|
||||
if (IsChangingRecipe || _removingTask) return;
|
||||
if (IsBusy) return;
|
||||
switch (cmd)
|
||||
{
|
||||
case "New":
|
||||
var newTask = new Workflow();
|
||||
var newTask = new Workflow { RecipeID = GlobalModel.CurrentRecipe.ID };
|
||||
newTask.Code =
|
||||
@"
|
||||
using System;
|
||||
@ -143,48 +144,7 @@ public class Extension_" + newTask.ID.ToString().Replace("-", "") +
|
||||
break;
|
||||
|
||||
case "Save":
|
||||
var names = new List<string>();
|
||||
|
||||
foreach (var item in Workflows)
|
||||
{
|
||||
if (string.IsNullOrEmpty(item.Name))
|
||||
{
|
||||
SendInfoDialog($"保存失败,名称{item.Name}不合适!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (names.Contains(item.Name))
|
||||
{
|
||||
SendInfoDialog($"保存失败,重复的名称{item.Name}!");
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
names.Add(item.Name);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var item in Workflows)
|
||||
{
|
||||
if (_DatasContext.Workflows.Any(h => h.ID == item.ID) == false)
|
||||
{
|
||||
item.RecipeID = _DatasContext.CurrentRecipe.ID;
|
||||
_DatasContext.Workflows.Add(item);
|
||||
}
|
||||
else
|
||||
{
|
||||
var newitem = _DatasContext.Workflows.Where(c => c.ID == item.ID).FirstOrDefault();
|
||||
|
||||
newitem.RecipeID = item.RecipeID;
|
||||
newitem.Name = item.Name;
|
||||
newitem.Code = item.Code;
|
||||
newitem.Comment = item.Comment;
|
||||
newitem.CycleDelayTime = item.CycleDelayTime;
|
||||
newitem.AutomaticExecution = item.AutomaticExecution;
|
||||
}
|
||||
}
|
||||
SelectedTask.Prompt = "";
|
||||
_DatasContext.Save();
|
||||
GlobalModel.SaveProject();
|
||||
break;
|
||||
|
||||
case "Config":
|
||||
@ -210,13 +170,14 @@ public class Extension_" + newTask.ID.ToString().Replace("-", "") +
|
||||
try
|
||||
{
|
||||
await selected.StopAsync();
|
||||
var task = _DatasContext.Workflows.FirstOrDefault(c => c.ID == selected.ID);
|
||||
if (task != null)
|
||||
var index = Workflows.IndexOf(selected);
|
||||
Workflows.RemoveAt(index);
|
||||
if (!GlobalModel.SaveProject())
|
||||
{
|
||||
_DatasContext.Workflows.Remove(task);
|
||||
_DatasContext.Save();
|
||||
Workflows.Insert(index, selected);
|
||||
selected.Start(GlobalModel);
|
||||
return;
|
||||
}
|
||||
Workflows.Remove(selected);
|
||||
SendInfoDialog($"已删除:{selected.Name}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
180
Tests/PLCSharp.Tests/PortableConfigurationTests.cs
Normal file
180
Tests/PLCSharp.Tests/PortableConfigurationTests.cs
Normal file
@ -0,0 +1,180 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Prism.Container.DryIoc;
|
||||
using Prism.Ioc;
|
||||
using PLCSharp.Models;
|
||||
using PLCSharp.VVMs.Connects;
|
||||
using PLCSharp.VVMs.Cylinders;
|
||||
using PLCSharp.VVMs.GlobalVariables;
|
||||
using PLCSharp.VVMs.Homepage;
|
||||
using PLCSharp.VVMs.MotionController;
|
||||
using PLCSharp.VVMs.Recipe;
|
||||
using PLCSharp.VVMs.Robots;
|
||||
using PLCSharp.VVMs.Vision;
|
||||
using PLCSharp.VVMs.Vision.Camera;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace PLCSharp.Tests;
|
||||
|
||||
public class PortableConfigurationTests
|
||||
{
|
||||
[Fact]
|
||||
public void CopyRestoresAllConfigurationInAnEmptyWorkingDatabase()
|
||||
{
|
||||
var sandbox = Directory.CreateTempSubdirectory();
|
||||
try
|
||||
{
|
||||
var source = Path.Combine(sandbox.FullName, "机器 A");
|
||||
var target = Path.Combine(sandbox.FullName, "机器 B");
|
||||
var image = Path.Combine(sandbox.FullName, "source.png");
|
||||
WriteFixture(source, image);
|
||||
var archive = Path.Combine(sandbox.FullName, "project.zip");
|
||||
ZipFile.CreateFromDirectory(source, archive);
|
||||
ZipFile.ExtractToDirectory(archive, target);
|
||||
Directory.Delete(source, true);
|
||||
File.Delete(image);
|
||||
VerifyCopy(target);
|
||||
}
|
||||
finally { sandbox.Delete(true); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ModuleSaveDetectsConflictAndCanRetryWithoutSavingWorkflowDraft()
|
||||
{
|
||||
var folder = Directory.CreateTempSubdirectory();
|
||||
try
|
||||
{
|
||||
using var project = ProjectDirectory.New();
|
||||
var variable = new Variable { RecipeID = project.DefaultRecipeId, Name = "V" };
|
||||
project.Data.Add(variable);
|
||||
project.Save(folder.FullName);
|
||||
project.Flows(project.DefaultRecipeId).Add(new PLCSharp.VVMs.Workflows.Workflow { Name = "Draft" });
|
||||
var file = Path.Combine(folder.FullName, "configuration", "variables.json");
|
||||
var before = File.ReadAllText(file);
|
||||
File.WriteAllText(file, before + " ");
|
||||
variable.Comment = "updated";
|
||||
Assert.Throws<IOException>(() => project.Data.Save());
|
||||
Assert.Equal(before + " ", File.ReadAllText(file));
|
||||
File.WriteAllText(file, before);
|
||||
project.Data.Save();
|
||||
using var copy = ProjectDirectory.Open(folder.FullName);
|
||||
Assert.Equal("updated", copy.Data.Variables.Single().Comment);
|
||||
Assert.Empty(copy.Flows(copy.DefaultRecipeId));
|
||||
var snapshot = Directory.GetFiles(folder.FullName, "*", SearchOption.AllDirectories)
|
||||
.ToDictionary(path => path, File.ReadAllText);
|
||||
copy.Save();
|
||||
Assert.All(snapshot, pair => Assert.Equal(pair.Value, File.ReadAllText(pair.Key)));
|
||||
}
|
||||
finally { folder.Delete(true); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FreshMachineDatabaseContainsOnlyAccountsAndLogs()
|
||||
{
|
||||
var folder = Directory.CreateTempSubdirectory();
|
||||
try
|
||||
{
|
||||
using var db = new MachineDataContext(Path.Combine(folder.FullName, "machine.db"));
|
||||
Assert.Equal(new[] { "ErrorLogs", "Users" }, db.Model.GetEntityTypes()
|
||||
.Select(t => t.GetTableName()).Order().ToArray());
|
||||
}
|
||||
finally
|
||||
{
|
||||
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
||||
folder.Delete(true);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly byte[] png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC");
|
||||
|
||||
internal static void WriteFixture(string source, string image)
|
||||
{
|
||||
File.WriteAllBytes(image, png);
|
||||
using (var project = ProjectDirectory.New())
|
||||
{
|
||||
var db = project.Data;
|
||||
var recipe = project.DefaultRecipeId;
|
||||
var other = new Recipe { Name = "B" };
|
||||
project.Recipes.Add(other);
|
||||
project.Flows(recipe).Add(new PLCSharp.VVMs.Workflows.Workflow { RecipeID = recipe,
|
||||
Name = "搬运", Code = "// portability fixture" });
|
||||
var robot = new Robot { Name = "R1" };
|
||||
var vision = new VisionFunction { RecipeID = recipe, Name = "检查" };
|
||||
var input = new VisionFlow { Type = VisionFlowType.从文件获取图片 };
|
||||
input.StringParams["Path"] = image;
|
||||
vision.VisionFlows.Add(input);
|
||||
db.AddRange(new Controller(), new Axis { Name = "X" }, new DI { Number = 3 }, new DQ { Number = 6 },
|
||||
new Connect { Name = "PLC", IP_SerialPort = "192.0.2.1", Params = new Connect.ConnectParams { UnitId = 12, BaudRate = 115200 } }, robot, new Cylinder { Name = "夹具" },
|
||||
new CameraBase { Name = "CAM1", Brand = CameraBrand.HikRobot },
|
||||
new Variable { RecipeID = recipe, Name = "计数", Comment = "A", Type = VariableDataType.Int32, DefaultValueStr = "35", ValueStr = "42", RetainPersistent = true },
|
||||
new Variable { RecipeID = other.ID, Name = "计数", Comment = "B" },
|
||||
new SystemVariable { RecipeID = recipe, Name = "状态" },
|
||||
new AxisPoint { RecipeID = recipe, Name = "定位", AxisXName = "X", X = 12.5 },
|
||||
new Matrix { RecipeID = recipe, StartName = "定位" },
|
||||
new InterpolationGroup { RecipeID = recipe, AxisXName = "X" },
|
||||
new RobotPoint { RecipeID = recipe, RobotID = robot.ID, Name = "P1", X = 19.25 },
|
||||
new RobotMatrix { RecipeID = recipe, RobotID = robot.ID, StartName = "P1" },
|
||||
vision, new CanvasConfig { RecipeID = recipe, Rows = 3 }, new CustomControl { RecipeID = recipe, Name = "显示" });
|
||||
db.Save();
|
||||
// Insert original PNG bytes directly so the portability test can run without a camera SDK.
|
||||
db.Database.ExecuteSqlInterpolated($"INSERT INTO ImageDatas (ID, RecipeID, Name, Mat) VALUES ({Guid.NewGuid()}, {recipe}, {"模板"}, {png})");
|
||||
db.Database.ExecuteSqlInterpolated($"INSERT INTO LocalImageDatas (ID, FuncID, Name, Mat) VALUES ({Guid.NewGuid()}, {vision.ID}, {"局部"}, {png})");
|
||||
project.Save(source);
|
||||
db.AxisPoints.Single().X = 13.75;
|
||||
db.Save(); // The regular module Save must update the directory as well.
|
||||
}
|
||||
}
|
||||
|
||||
internal static void VerifyCopy(string target)
|
||||
{
|
||||
Assert.Empty(Directory.GetFiles(target, "*.db*", SearchOption.AllDirectories));
|
||||
using var copy = ProjectDirectory.Open(target);
|
||||
Assert.Equal("// portability fixture", copy.Flows(copy.DefaultRecipeId).Single().Code);
|
||||
var restored = copy.Data;
|
||||
Assert.Equal("Data Source=:memory:", restored.Database.GetConnectionString());
|
||||
var connection = restored.Connects.Single();
|
||||
Assert.Equal("192.0.2.1", connection.IP_SerialPort);
|
||||
Assert.Equal(12, connection.Params.UnitId);
|
||||
Assert.Equal(115200, connection.Params.BaudRate);
|
||||
Assert.Single(restored.Controllers);
|
||||
Assert.Equal(3, restored.DI.Single().Number);
|
||||
Assert.Equal(6, restored.DQ.Single().Number);
|
||||
Assert.Equal("夹具", restored.Cylinders.Single().Name);
|
||||
Assert.Equal("CAM1", restored.Cameras.Single().Name);
|
||||
var point = restored.AxisPoints.Single();
|
||||
Assert.Equal(13.75, point.X);
|
||||
Assert.Equal(restored.Axes.Single().Name, point.AxisXName);
|
||||
Assert.Equal(point.Name, restored.Matrices.Single().StartName);
|
||||
Assert.Equal(point.AxisXName, restored.InterpolationGroups.Single().AxisXName);
|
||||
Assert.Equal(restored.Robots.Single().ID, restored.RobotPoints.Single().RobotID);
|
||||
Assert.Equal(restored.RobotPoints.Single().Name, restored.RobotMatrices.Single().StartName);
|
||||
var counter = restored.Variables.Single(v => v.RecipeID == copy.DefaultRecipeId);
|
||||
Assert.Equal("A", counter.Comment);
|
||||
Assert.True(counter.RetainPersistent);
|
||||
Assert.Equal("35", counter.DefaultValueStr);
|
||||
Assert.Equal("42", counter.ValueStr);
|
||||
Assert.Equal("B", restored.Variables.Single(v => v.RecipeID != copy.DefaultRecipeId).Comment);
|
||||
IContainerExtension container = new DryIocContainerExtension();
|
||||
container.RegisterInstance(restored);
|
||||
var variables = new VariablesModel(container, null!, null!);
|
||||
variables.LoadRecipe(copy.DefaultRecipeId);
|
||||
Assert.Equal(42, (int)variables.Variables.Single().Value);
|
||||
Assert.Equal("状态", variables.SystemVariables.Single().Name);
|
||||
Assert.Null((object?)variables.SystemVariables.Single().Value);
|
||||
var function = restored.VisionFunctions.Single();
|
||||
var step = Assert.Single(function.VisionFlows);
|
||||
Assert.Equal(png, Convert.FromBase64String(step.StringParams["ImageBase64"]));
|
||||
Assert.Equal("source.png", step.StringParams["Path"]);
|
||||
Assert.True(new PLCSharp.VVMs.Vision.VisionFlowHandler.Access.ImageFromFileHandler().Execute(function, step));
|
||||
Assert.Equal(1, function.Src.Width);
|
||||
Assert.Equal(1, function.Src.Height);
|
||||
function.Src.Dispose();
|
||||
Assert.Equal(function.ID, restored.LocalImageDatas.Select(i => i.FuncID).Single());
|
||||
Assert.Equal(png, restored.ImageDatas.Select(i => i.SerializedMat).Single());
|
||||
Assert.Equal(png, restored.LocalImageDatas.Select(i => i.SerializedMat).Single());
|
||||
Assert.Equal(3, restored.CanvasConfigs.Single().Rows);
|
||||
Assert.Equal("显示", restored.CustomControls.Single().Name);
|
||||
Assert.Empty(restored.Users);
|
||||
Assert.Empty(restored.ErrorLogs);
|
||||
}
|
||||
}
|
||||
86
Tests/PLCSharp.Tests/ProjectDirectoryTests.cs
Normal file
86
Tests/PLCSharp.Tests/ProjectDirectoryTests.cs
Normal file
@ -0,0 +1,86 @@
|
||||
using PLCSharp.Models;
|
||||
using PLCSharp.VVMs.Recipe;
|
||||
using PLCSharp.VVMs.Workflows;
|
||||
using System.IO;
|
||||
|
||||
namespace PLCSharp.Tests;
|
||||
|
||||
public class ProjectDirectoryTests
|
||||
{
|
||||
[Fact]
|
||||
public void CopiedDirectoryOpensIndependentlyAndOnlyChangedScriptIsRewritten()
|
||||
{
|
||||
var sandbox = Directory.CreateTempSubdirectory();
|
||||
try
|
||||
{
|
||||
var source = Path.Combine(sandbox.FullName, "工站 A");
|
||||
var copy = Path.Combine(sandbox.FullName, "工站 副本");
|
||||
var project = ProjectDirectory.New();
|
||||
var second = new Recipe { Name = "配方 B", Comment = "测试备注" };
|
||||
project.Recipes.Add(second);
|
||||
var flow = new Workflow { Name = "送料", RecipeID = second.ID, Comment = "循环",
|
||||
CycleDelayTime = 0.125, Code = "// 独立脚本\r\n", AutomaticExecution = true };
|
||||
project.Flows(second.ID).Add(flow);
|
||||
project.Save(source);
|
||||
foreach (var file in Directory.GetFiles(source, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var target = Path.Combine(copy, Path.GetRelativePath(source, file));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
File.Copy(file, target);
|
||||
}
|
||||
Directory.Move(source, source + ".moved");
|
||||
var opened = ProjectDirectory.Open(copy);
|
||||
Assert.Equal(project.Id, opened.Id);
|
||||
Assert.Equal(project.DefaultRecipeId, opened.DefaultRecipeId);
|
||||
Assert.Equal("测试备注", opened.Recipes.Single(r => r.ID == second.ID).Comment);
|
||||
var script = Assert.Single(opened.Flows(second.ID));
|
||||
Assert.Equal(flow.ID, script.ID);
|
||||
Assert.Equal(flow.Code, script.Code);
|
||||
Assert.Equal(flow.Name, script.Name);
|
||||
Assert.Equal(flow.CycleDelayTime, script.CycleDelayTime);
|
||||
Assert.True(script.AutomaticExecution);
|
||||
Assert.False(opened.HasChanges);
|
||||
|
||||
var before = Directory.GetFiles(copy, "*", SearchOption.AllDirectories).ToDictionary(p => p, File.ReadAllText);
|
||||
script.Code += "// edit\n";
|
||||
opened.Save();
|
||||
var changed = Assert.Single(before.Where(p => File.ReadAllText(p.Key) != p.Value));
|
||||
Assert.EndsWith(".cs", changed.Key);
|
||||
Assert.Equal(script.Code, ProjectDirectory.Open(copy).Flows(second.ID).Single().Code);
|
||||
File.WriteAllText(changed.Key, "// external edit");
|
||||
Assert.Throws<IOException>(() => opened.Save());
|
||||
Assert.Equal("// external edit", File.ReadAllText(changed.Key));
|
||||
File.Delete(changed.Key);
|
||||
Assert.Throws<FileNotFoundException>(() => ProjectDirectory.Open(copy));
|
||||
}
|
||||
finally { sandbox.Delete(true); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FailedMultiFileSaveRestoresOriginalScriptAndCanBeRetried()
|
||||
{
|
||||
var folder = Directory.CreateTempSubdirectory();
|
||||
try
|
||||
{
|
||||
var project = ProjectDirectory.New();
|
||||
var flows = project.Flows(project.DefaultRecipeId);
|
||||
var first = new Workflow { Name = "First", Code = "// original" };
|
||||
flows.Add(first);
|
||||
project.Save(folder.FullName);
|
||||
|
||||
first.Code = "// updated";
|
||||
var next = new Workflow { Name = "Second", Code = "// second" };
|
||||
flows.Add(next);
|
||||
var scripts = Path.GetDirectoryName(Directory.GetFiles(folder.FullName, "*.cs", SearchOption.AllDirectories).Single())!;
|
||||
var occupiedPath = Directory.CreateDirectory(Path.Combine(scripts, next.ID + ".cs"));
|
||||
Assert.Throws<IOException>(() => project.Save());
|
||||
Assert.Equal("// original", File.ReadAllText(Path.Combine(scripts, first.ID + ".cs")));
|
||||
Assert.Single(ProjectDirectory.Open(folder.FullName).Flows(project.DefaultRecipeId));
|
||||
|
||||
occupiedPath.Delete();
|
||||
project.Save();
|
||||
Assert.Equal(2, ProjectDirectory.Open(folder.FullName).Flows(project.DefaultRecipeId).Count);
|
||||
}
|
||||
finally { folder.Delete(true); }
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user