plcsharp/PLCSharpWpf/Models/WorkflowScriptApi.cs

129 lines
8.0 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using PLCSharp.Core.Common;
using PLCSharp.VVMs.Vision;
using PLCSharp.VVMs.Workflows;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace PLCSharp.Models;
internal static class WorkflowScriptApi
{
private sealed record Member(Type Owner, string Name, string Conditions, string Completion, string Failure)
{
public string Signature
{
get
{
var method = Owner.GetMethods().Single(m => m.Name == Name);
var args = method.GetParameters().Select(p => $"{TypeName(p.ParameterType)} {p.Name}");
return $"{TypeName(method.ReturnType)} {Owner.Name}.{Name}({string.Join(", ", args)})";
}
}
private static string TypeName(Type t) =>
t == typeof(void) ? "void" : t == typeof(string) ? "string" : t == typeof(bool) ? "bool" :
t == typeof(double) ? "double" : t.IsGenericType ?
$"{t.Name.Split('`')[0]}<{string.Join(", ", t.GetGenericArguments().Select(TypeName))}>" : t.Name;
}
private static Member Lookup(string method, string failure) =>
new(typeof(GlobalModel), method, "使用工程中已配置的对象名称;配方对象取当前配方。", "同步返回对象。", failure);
private static readonly Dictionary<string, Member[]> Topics = new(StringComparer.OrdinalIgnoreCase)
{
["workflow"] = [
Lookup(nameof(GlobalModel.GetTask), "找不到工作流时返回 null。"),
new(typeof(Workflow), nameof(Workflow.Run),
"调用已在运行时编译的工作流。停止中、已有运行、无入口、未编译、异常状态或编译后不足 3 秒时会直接返回。避免递归调度。",
"同步执行一次 Run 入口。返回 void,没有表示本次是否实际执行的返回值。多步脚本须自行约定 Flow.Completed/Success。",
"工作流捕获入口异常,设置 Exception 并写 DebugLog。调用方检查 Exception;仅凭 Run 返回不能判定业务成功。")],
["vision"] = [
Lookup(nameof(GlobalModel.GetVisionFunction), "找不到视觉功能时抛出异常。"),
new(typeof(VisionFunction), nameof(VisionFunction.RunAllAsync),
"功能必须属于已加载的当前配方。一次独立检查前调用其 Flow.Reset();同一视觉实例共享步骤、图像和结果,避免并发或重入。",
"等待整个 Task 后读取功能自身的 Flow.Success。同步脚本由 WPF 界面线程调用时不能直接阻塞尚未完成的 Task;见本主题示例。后台线程可 GetAwaiter().GetResult()。",
"返回的 bool 即使在步骤失败或超时时也可能为 true。步骤失败详情在对应 VisionFlows 步骤的 Flow.FailMessage 中。等待时也可能抛异常。超时步骤可能仍在后台结束。")],
["flow"] = [
new(typeof(FlowModel), nameof(FlowModel.Reset), "仅在开始独立操作时调用。", "同步重置 Step、Completed、Success、FailMessage 及计时起点。", "不会等待或取消正在执行的任务。"),
new(typeof(FlowModel), nameof(FlowModel.CheckStepTime), "second 单位为秒。", "同步返回当前步骤是否超过时限。", "返回 true 表示超时;不自动中止流程。"),
new(typeof(FlowModel), nameof(FlowModel.CheckFlowTime), "second 单位为秒。", "同步返回整个流程是否超过时限。", "返回 true 表示超时;不自动中止流程。")],
["lookup"] = [
Lookup(nameof(GlobalModel.GetVariable), "找不到变量时抛异常。"), Lookup(nameof(GlobalModel.GetImageData), "找不到图像或 Mat 为 null 时抛异常。"),
Lookup(nameof(GlobalModel.GetCustomControl), "名称为空或找不到控件时返回 null。"), Lookup(nameof(GlobalModel.GetImageControl), "名称为空、未找到或控件类型不匹配时返回 null。"),
Lookup(nameof(GlobalModel.GetRobot), "未配置时抛异常。"), Lookup(nameof(GlobalModel.GetConnect), "未配置时抛异常。")]
};
private const string VisionExample = """
using System;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using PLCSharp.Models;
using PLCSharp.Core.Common;
public class Extension___WORKFLOW_ID__
{
public void Run(GlobalModel model, FlowModel flow)
{
var check = model.GetVisionFunction("检查");
check.Flow.Reset();
var run = check.RunAllAsync();
if (!run.IsCompleted && Application.Current.Dispatcher.CheckAccess())
{
var frame = new DispatcherFrame();
run.GetAwaiter().OnCompleted(() => frame.Continue = false);
Dispatcher.PushFrame(frame);
}
run.GetAwaiter().GetResult();
if (!check.Flow.Success)
{
var failed = check.VisionFlows.FirstOrDefault(step => !string.IsNullOrEmpty(step.Flow.FailMessage));
throw new InvalidOperationException(failed?.Flow.FailMessage ?? "视觉检查失败");
}
}
}
""";
private const string CallerExample = """
using System;
using PLCSharp.Models;
using PLCSharp.Core.Common;
public class Extension___WORKFLOW_ID__
{
public void Run(GlobalModel model, FlowModel flow)
{
var target = model.GetTask("执行视觉检查") ?? throw new InvalidOperationException("找不到执行视觉检查");
if (!target.IsCompiled || target.Exception || target.IsRuning || target.CompiledTime.AddSeconds(3) > DateTime.Now)
throw new InvalidOperationException("执行视觉检查尚未就绪");
target.Run(model);
if (target.Exception)
throw new InvalidOperationException("执行视觉检查异常:" + target.DebugLog);
}
}
""";
internal static JsonNode Read(string topic, Guid? workflowId)
{
var assembly = typeof(GlobalModel).Assembly;
var name = assembly.GetName();
var selected = string.IsNullOrWhiteSpace(topic) ? Topics : Topics.Where(kv =>
kv.Key.Equals(topic, StringComparison.OrdinalIgnoreCase) || kv.Value.Any(m =>
m.Name.Equals(topic, StringComparison.OrdinalIgnoreCase) ||
$"{m.Owner.Name}.{m.Name}".Equals(topic, StringComparison.OrdinalIgnoreCase))).ToDictionary();
if (selected.Count == 0) throw new ArgumentException("未知主题或方法。省略 topic 可列出全部主题。");
string Example(string template) => workflowId is Guid id ? template.Replace("__WORKFLOW_ID__", id.ToString("N")) : template;
return JsonSerializer.SerializeToNode(new {
assembly = name.Name, version = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? name.Version?.ToString(),
buildId = assembly.ManifestModule.ModuleVersionId,
entry = "public void Run(GlobalModel model, FlowModel flow);公开可无参构造的 Extension_<工作流ID的32位十六进制> 类。入口必须同步完成,不能使用 async void 或启动未等待的任务。",
examples = "新建工作流时直接使用模板,preview_batch 在分配 ID 后替换 __WORKFLOW_ID__。修改已有脚本可传 workflowId 获取真实类名,只合并所需语句。预览编译不执行代码;保存后仍须在运行时编译才能执行。",
topics = selected.Select(kv => new { topic = kv.Key,
members = kv.Value.Select(m => new { signature = m.Signature, conditions = m.Conditions, completion = m.Completion, failure = m.Failure }),
example = kv.Key switch { "vision" => Example(VisionExample), "workflow" => Example(CallerExample), _ => null } })
});
}
}