plcsharp/PLCSharpWpf/VVMs/Workflows/Workflow.cs
2026-12-05 20:01:10 +08:00

411 lines
12 KiB
C#

using PLCSharp.Core.Prism;
using PLCSharp.Core.Common;
using PLCSharp.Models;
using Prism.Commands;
using Prism.Mvvm;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
namespace PLCSharp.VVMs.Workflows
{
/// <summary>
/// 工作流
/// </summary>
public class Workflow : BindableBase
{
/// <summary>
/// 唯一标识
/// </summary>
[Key]
public Guid ID { get; set; } = Guid.NewGuid();
/// <summary>
/// 配方标识
/// </summary>
public Guid RecipeID { get; set; }
private string _Name;
/// <summary>
/// 配置项
/// </summary>
public string Name
{
get { return _Name; }
set
{
if (_Name != value)
{
Prompt = "已修改,请保存";
}
SetProperty(ref _Name, value);
}
}
private string _Prompt;
/// <summary>
/// 提示
/// </summary>
[NotMapped]
public string Prompt
{
get { return _Prompt; }
set { SetProperty(ref _Prompt, value); }
}
private double _CycleDelayTime = 0.01;
/// <summary>
/// 循环结束延迟
/// </summary>
public double CycleDelayTime
{
get { return _CycleDelayTime; }
set
{
if (_CycleDelayTime != value)
{
Prompt = "已修改,请保存";
}
SetProperty(ref _CycleDelayTime, value);
}
}
private string _Code;
private double _CycleTime;
/// <summary>
/// CycleTime
/// </summary>
[NotMapped]
public double CycleTime
{
get { return _CycleTime; }
set { SetProperty(ref _CycleTime, value); }
}
/// <summary>
/// 配置项
/// </summary>
public string Code
{
get { return _Code; }
set
{
if (_Code != value)
{
IsCompiled = false;
Prompt = "已修改,请编译";
}
SetProperty(ref _Code, value);
}
}
private string _Comment;
/// <summary>
/// 备注
/// </summary>
public string Comment
{
get { return _Comment; }
set
{
if (_Comment != value)
{
Prompt = "已修改,请保存";
}
SetProperty(ref _Comment, value);
}
}
private bool _AutomaticExecution;
/// <summary>
/// 脚本自动运行
/// </summary>
public bool AutomaticExecution
{
get { return _AutomaticExecution; }
set
{
if (_AutomaticExecution != value)
{
Prompt = "已修改,请保存";
}
SetProperty(ref _AutomaticExecution, value);
}
}
/// <summary>
/// 编译时间
/// </summary>
[NotMapped]
public DateTime CompiledTime { get; set; } = DateTime.Now;
private bool _IsCompiled;
/// <summary>
/// IsCompiled
/// </summary>
[NotMapped]
public bool IsCompiled
{
get { return _IsCompiled; }
set { SetProperty(ref _IsCompiled, value); }
}
private bool _IsRuning;
/// <summary>
/// IsRuning
/// </summary>
[NotMapped]
public bool IsRuning
{
get { return _IsRuning; }
set { SetProperty(ref _IsRuning, value); }
}
/// <summary>
/// Assembly
/// </summary>
[NotMapped]
public Assembly Assembly { get; set; }
private string _DebugLog;
/// <summary>
/// Debug日志
/// </summary>
[NotMapped]
public string DebugLog
{
get { return _DebugLog; }
set { SetProperty(ref _DebugLog, value); }
}
private bool _Exception;
/// <summary>
/// 异常
/// </summary>
[NotMapped]
public bool Exception
{
get { return _Exception; }
set { SetProperty(ref _Exception, value); }
}
private AssemblyCSharpBuilder AssemblyCSharpBuilder;
private NatashaLoadContext _loadContext;
private DelegateCommand _Compile;
/// <summary>
/// 编译
/// </summary>
public DelegateCommand Compile =>
_Compile ??= new DelegateCommand(ExecuteCompile);
private void ExecuteCompile()
{
lock (_executionGate)
{
try
{
if (IsRuning || _activeRun != null)
{
DebugLog += "正在运行中,请先停止后再编译。\n";
return;
}
Flow.Reset();
// 卸载上一次编译的动态程序集域,避免每次编译的程序集永久驻留内存(无法被 GC 回收)
UnloadDomain();
// 新建可卸载的加载上下文(域),编译产物加载进该域,下次编译时可整体卸载
_loadContext = NatashaManagement.CreateRandomDomain();
AssemblyCSharpBuilder = new();
AssemblyCSharpBuilder.LoadContext = _loadContext;
// 新域没有 Preheating 预热的内存引用,合并主域(默认域)引用保证脚本能引用 PLCSharp 类型
AssemblyCSharpBuilder.WithCombineReferences(item => item.UseAllReferences());
DebugLog = "编译中,请稍等。\n";
AssemblyCSharpBuilder.ConfigLoadContext(ctx => ctx.AddReferenceAndUsingCode<object>());
AssemblyCSharpBuilder.Add(Code);
AssemblyCSharpBuilder.LogCompilationEvent += OnCompilationLog;
Assembly = AssemblyCSharpBuilder.GetAssembly();
DebugLog += "编译完成。\n";
Prompt = "";
IsCompiled = true;
Exception = false;
var typeName = "Extension_" + ID.ToString().Replace("-", "");
var extType = Assembly.GetTypes().FirstOrDefault(t => t.Name == typeName || t.FullName == typeName);
if (extType != null)
{
var instance = Activator.CreateInstance(extType)!;
action = Assembly.GetDelegateFromShortName<Action<GlobalModel, FlowModel>>(typeName, "Run", target: instance);
}
else
{
DebugLog += "编译错误:无法找到 Extension 类型。\n";
}
}
catch (Exception e)
{
IsCompiled = false;
Exception = true;
DebugLog += e.Message;
}
}
}
/// <summary>
/// 卸载动态程序集域
/// </summary>
private void UnloadDomain()
{
// 先释放对旧程序集的所有强引用,否则 AssemblyLoadContext 无法真正卸载
action = null;
Assembly = null;
AssemblyCSharpBuilder = null;
_loadContext?.Dispose();
_loadContext = null;
}
/// <summary>
/// 编译日志
/// </summary>
private void OnCompilationLog(NatashaCompilationLog log)
{
DebugLog += log.ToString();
}
private Action<GlobalModel, FlowModel> action;
/// <summary>
/// 运行
/// </summary>
/// <param name="globalModel">全局模型</param>
public void Run(GlobalModel globalModel)
{
lock (_executionGate)
{
if (_stopped || _activeRun != null || action == null || !IsCompiled || Exception)
return;
if (CompiledTime.AddSeconds(3) > DateTime.Now) return;
_activeRun = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
try
{
IsRuning = true;
action(globalModel, Flow);
}
catch (Exception ex)
{
Exception = true;
DebugLog += $"运行时异常: {ex}\n";
globalModel.SendErr($"运行时异常: {ex}\n");
}
finally
{
lock (_executionGate)
{
IsRuning = AutomaticExecution && !_stopped && !Exception;
_activeRun.TrySetResult();
_activeRun = null;
}
}
}
private readonly object _executionGate = new();
private TaskCompletionSource _activeRun;
private CancellationTokenSource _scanCancellation;
private Task _scan = Task.CompletedTask;
private bool _stopped;
public void Start(GlobalModel globalModel)
{
lock (_executionGate)
{
if (!_scan.IsCompleted || _activeRun != null) return;
_scanCancellation?.Dispose();
_scanCancellation = new();
_stopped = false;
var token = _scanCancellation.Token;
_scan = Task.Run(() => ScanAsync(globalModel, token));
}
}
// 保留脚本可调用的停止请求入口。替换配方或删除任务时必须等待 StopAsync。
public void Stop() => _ = StopAsync();
public Task StopAsync()
{
lock (_executionGate)
{
_stopped = true;
var canceled = _scanCancellation?.CancelAsync() ?? Task.CompletedTask;
if (_activeRun == null)
{
IsRuning = false;
return Task.WhenAll(_scan, canceled);
}
return Task.WhenAll(_scan, canceled, _activeRun.Task);
}
}
private async Task ScanAsync(GlobalModel globalModel, CancellationToken token)
{
var sw = new Stopwatch();
try
{
while (!token.IsCancellationRequested)
{
sw.Restart();
await Task.Delay((int)(CycleDelayTime * 1000), token).ConfigureAwait(false);
if (AutomaticExecution)
Run(globalModel);
else
{
lock (_executionGate)
{
if (_activeRun == null) IsRuning = false;
}
}
sw.Stop();
if (!AutomaticExecution)
await Task.Delay(1000, token).ConfigureAwait(false);
CycleTime = sw.Elapsed.TotalSeconds;
if (Exception)
globalModel.ModeState.Sc.Stop = true;
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
catch (Exception ex)
{
WorkerGuard.Report($"工艺流程扫描 异常停止:{ex}");
}
}
private FlowModel _Flow = new();
/// <summary>
/// 流程状态模型
/// </summary>
[NotMapped]
public FlowModel Flow
{
get { return _Flow; }
set { SetProperty(ref _Flow, value); }
}
}
}