OpenRobot.Edge.Decision 0.1.0

dotnet add package OpenRobot.Edge.Decision --version 0.1.0
                    
NuGet\Install-Package OpenRobot.Edge.Decision -Version 0.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OpenRobot.Edge.Decision" Version="0.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OpenRobot.Edge.Decision" Version="0.1.0" />
                    
Directory.Packages.props
<PackageReference Include="OpenRobot.Edge.Decision" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add OpenRobot.Edge.Decision --version 0.1.0
                    
#r "nuget: OpenRobot.Edge.Decision, 0.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package OpenRobot.Edge.Decision@0.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=OpenRobot.Edge.Decision&version=0.1.0
                    
Install as a Cake Addin
#tool nuget:?package=OpenRobot.Edge.Decision&version=0.1.0
                    
Install as a Cake Tool

OpenRobot.Edge.Decision

边端控制方法的调用时机编排类库:拦截一次已经发起的调用,按规则决定立即放行还是缓存等待, 等事件、延时、变量条件满足后再放行。

纯逻辑、无 I/O:

  • 不依赖 AppSdk、ASP.NET Core、EF Core;
  • 不落库、不发 IPC、不做定时器;
  • 落库、派发、事件订阅、时钟全部由宿主注入。

平台侧(EdgeWebApi)的完整落地见 docs/tasks/task-30-progress.md。

目录

1. 它解决什么问题

业务调用控制方法时,经常不能立刻执行:

  • 报警后要等当前刀具加工完成;
  • 不同刀型策略不同(立即 / 延迟 / 等状态);
  • 变量越过阈值并保持一段时间才动作;
  • 延时执行,期间条件消失就取消。

这个库只做一件事:给定「一次调用 + 当前上下文 + 一组规则」,算出该不该等、等到什么时候。 它不替业务发起调用,也不改参数:参数在拦截那一刻固化,放行时原样使用。

2. 核心概念

概念 类型 说明
规则 DecisionRule 匹配范围 + 触发条件 + 保护策略
原始调用 DecisionInvocation 目标方法、参数、调用方、收到时间
上下文 DecisionContext 调用方、机床、刀具、流程、状态、context 快照
触发 DecisionTrigger 立即 / 延时 / 事件 / 条件 / 组合
意图 DecisionIntent 正在等待的一次调用,Id 通常等于平台命令号
判定结果 DecisionPlan 是否等待、命中规则、到期时间
值源 IDecisionValueSource 稳定引用 → 当前值

执行流程:

业务调用 ──► engine.Plan(invocation, context)
                │
      ┌─────────┴─────────┐
      ▼                   ▼
 Deferred=false       Deferred=true
 立即放行             宿主落 waiting 记录
                        engine.Enqueue(intent, context)
                              │
        事件 / 变量 / 延时 ──► engine.Notify / NotifyValuesChanged / Tick
                              │
                        engine.Ready 事件
                              │
                         宿主真正下发

3. 规则模型

public sealed class DecisionRule
{
    public string Id { get; init; } = "";
    public string? Title { get; init; }
    public bool Enabled { get; init; } = true;
    public int Priority { get; init; }

    public DecisionScope Scope { get; init; } = new();
    public DecisionTrigger Trigger { get; init; } = new ImmediateTrigger();
    public DecisionPolicy Policy { get; init; } = new();
}

规则没有 Action:目标方法与参数来自被拦截的调用。

3.1 作用域

public sealed class DecisionScope
{
    public string? CallerApp { get; init; }    // 调用方
    public string? App { get; init; }          // 目标应用
    public string? MethodKey { get; init; }    // 目标方法
    public int? DeviceId { get; init; }
    public List<string>? ToolTypes { get; init; }
    public List<int>? ToolNumbers { get; init; }
    public string? ProcessId { get; init; }
    public string? State { get; init; }
    public List<DecisionCondition>? Conditions { get; init; }
}

未填的字段不限制;至少要限制一个字段或条件,否则校验不通过。 命中多条时按 Priority 降序取第一条。

3.2 保护策略

public sealed class DecisionPolicy
{
    public string? DedupeKey { get; init; }      // {device} {app} {caller} {method} {params.xxx}
    public int DedupeWindowMs { get; init; }
    public int MaxDelayMs { get; init; } = 600_000;
    public int DispatchTimeoutMs { get; init; } = 30_000;
    public DecisionRetryPolicy? Retry { get; init; }
}
  • DedupeKey 用 DecisionDedupe.Expand 展开;窗口内同一键只保留一条等待;
  • MaxDelayMs 决定 ExpireAt,超时由宿主标记过期;
  • Retry 由宿主在放行失败时使用,引擎本身不重试。

3.3 JSON 示例

{
  "id": "alarm-stop-wait-tool-change",
  "title": "报警停机调用:等换刀后再下发",
  "enabled": true,
  "priority": 100,
  "scope": {
    "callerApp": "UspeedPlus",
    "app": "DcProvider",
    "method": "device-control",
    "deviceId": 1,
    "conditions": [
      { "ref": "dc://dcprovider/1/850", "operator": "==", "value": 1 },
      { "ref": "biz://UspeedPlus/tool/type", "operator": "in", "value": ["T01", "T02"] },
      { "ref": "context://business.machine.mode", "operator": "==", "value": "auto" }
    ]
  },
  "trigger": { "kind": "event", "event": "tool.changed" },
  "policy": {
    "dedupeKey": "alarm:{device}:{method}:{params.address}",
    "dedupeWindowMs": 60000,
    "maxDelayMs": 600000,
    "retry": { "maxAttempts": 2, "delayMs": 1000 }
  }
}

反序列化:

var rule = JsonSerializer.Deserialize<DecisionRule>(json, DecisionJson.Default);

4. 触发器

kind 类型 字段 含义
immediate ImmediateTrigger — 命中即放行
delay DelayTrigger delayMs 拦截后等待固定时长
event EventTrigger event / filter / delayMs 等某类事件,可再延时
condition ConditionTrigger condition 条件成立并保持 holdMs
all / any / not CompositeTrigger items 组合子触发器
{ "kind": "delay", "delayMs": 5000 }
{
  "kind": "event",
  "event": "alarm.raised",
  "filter": { "code": 1001 },
  "delayMs": 0
}
{
  "kind": "condition",
  "condition": {
    "ref": "dc://dcprovider/1/900",
    "operator": ">",
    "value": 100,
    "holdMs": 2000
  }
}
{
  "kind": "all",
  "items": [
    { "kind": "event", "event": "tool.changed" },
    { "kind": "condition", "condition": { "ref": "biz://UspeedPlus/tool/type", "operator": "==", "value": "T01" } }
  ]
}

语义:

  • 条件从「不满足」变「满足」并连续保持 HoldMs 才成立;期间掉回不满足会清零;
  • 事件按 EventTrigger.Event 匹配,Filter 是事件载荷的子集相等;
  • not 只取第一个子项取反;复杂的否定条件建议直接写条件引用。

5. 条件与数据源

public sealed class DecisionCondition
{
    public string Ref { get; init; } = "";
    public string Operator { get; init; } = "==";
    public JsonElement? Value { get; init; }
    public int HoldMs { get; init; }
}

5.1 引用格式

前缀 含义 示例
dc:// 硬件采集变量 dc://dcprovider/1/850
biz:// 业务变量 biz://UspeedPlus/tool/type
config:// 平台配置 config://apps.DcProvider.Apply.DebounceMs
context://business.* 调用方业务快照 context://business.machine.mode
context://device.* 设备快照 context://device.cnc.model
context://runtime.* 运行时快照 context://runtime.executingProgram

dc / biz / config 走 VariableRef;context 由宿主值源按快照解析, 不修改 VariableRef 的白名单。

5.2 操作符

操作符 说明
== / != 相等 / 不等;数字跨类型按数值比较
> / >= / < / <= 数字比较;字符串按序比较
in 值在期望数组里
exists 引用存在且有值(不要求 Value)

数值字符串(如 DC 上报的 "12")与数字会按数值比较;布尔与布尔、字符串与字符串严格比较。 值缺失视为条件不满足。

5.3 实现值源

public sealed class MyValueSource : IDecisionValueSource
{
    public bool TryGet(string reference, string? callerApp, out JsonElement value)
    {
        // dc:// / biz:// 读变量缓存
        // config:// 读平台配置
        // context:// 读 callerApp 最近一份快照
        value = default;
        return false;
    }
}

callerApp 用于解析 context://——同一个引用对不同调用方可以是不同快照。 只测事件 / 延时的场景可以直接用 EmptyDecisionValueSource.Instance。

6. 快速开始

using OpenRobot.Edge.Decision;
using OpenRobot.Edge.Decision.Contracts;
using OpenRobot.Edge.Decision.Engine;

var options = new DecisionOptions();
var engine = new DecisionEngine(options, myValueSource, TimeProvider.System);

// 1. 载入规则(通常来自平台表 / 配置文件)
engine.UpdateRules(rules);

// 2. 业务调用到来
var invocation = new DecisionInvocation
{
    Id = commandId.ToString(),
    App = "DcProvider",
    Method = "device-control",
    Parameters = parameters,
    CallerApp = "UspeedPlus",
    RequestedAt = now,
    TimeoutMs = 10_000,
};

var context = new DecisionContext
{
    CallerApp = "UspeedPlus",
    DeviceId = 1,
    ToolType = "T01",
    Snapshot = snapshotNode,
};

var plan = engine.Plan(invocation, context);

if (!plan.Deferred)
{
    // 3a. 未命中 / 立即满足:直接下发
}
else
{
    // 3b. 落库(waiting 记录),再入队
    var intent = new DecisionIntent
    {
        Id = invocation.Id,
        RuleId = plan.Rule!.Id,
        RuleTitle = plan.Rule.Title,
        Priority = plan.Rule.Priority,
        Invocation = invocation,
        DedupeKey = plan.Rule.Policy.DedupeKey is { } key
            ? DecisionDedupe.Expand(key, invocation, context)
            : null,
        CreatedAt = now,
        DueAt = plan.DueAt ?? now,
        ExpireAt = plan.ExpireAt ?? now + plan.Rule.Policy.MaxDelayMs,
    };

    engine.Enqueue(intent, context);
}

// 4. 宿主订阅
engine.Ready += intent =>
{
    // 真正下发(例如调用平台 IControlMethodInvoker),并更新记录为 released
};

engine.Closed += intent =>
{
    // 取消 / 超时:更新记录为 cancelled / expired
};

// 5. 推进
engine.Notify(new DecisionEvent { Type = "tool.changed", Timestamp = now });
engine.NotifyValuesChanged();   // 变量或 context 快照变化后
engine.Tick();                  // 定时调用:延时到期、Hold 满足、等待超时

7. 宿主需要做什么

职责 说明
拦截 只在业务调用链路上调用 Plan;界面 / 云端手工调用不要进决策
落库 Deferred 时先写等待记录,再 Enqueue;记录 Id 与意图 Id 保持一致
派发 订阅 Ready,真正调用目标方法;失败 / 离线时自行重排队
关闭 订阅 Closed,把记录改成 cancelled / expired
事件 把 app.event.publish、变量变化、context 快照变化接到 Notify / NotifyValuesChanged
定时 按固定周期(建议 1 秒)调用 Tick
规则 存储、校验、热更新;删除 / 停用规则时调用 CancelByRule
重启 从等待记录重建 DecisionIntent 并 Enqueue;已过期的直接关闭
去重 可在落库层按 DedupeKey 查等待记录;引擎队列也提供 FindByDedupe

8. 校验、序列化与选项

var errors = DecisionRuleValidator.Validate(rules);
foreach (var error in errors)
{
    Console.WriteLine($"{error.RuleId} {error.Field}: {error.Message}");
}

校验内容:

  • Id 非空且唯一;
  • 作用域至少有一个限制;
  • 引用前缀与格式(dc:// / biz:// / config:// / context://business|device|runtime.*);
  • 操作符白名单;
  • DelayMs / MaxDelayMs / HoldMs 不超过 7 天;
  • 组合触发器至少一个子项。

序列化统一用 DecisionJson.Default(camelCase、枚举字符串、触发器多态)。

public sealed class DecisionOptions
{
    public int MaxPending { get; set; } = 1_000;
    public int DefaultMaxDelayMs { get; set; } = 600_000;
    public int DefaultDispatchTimeoutMs { get; set; } = 30_000;
    public DecisionContextPaths ContextPaths { get; set; } = new();
}

DecisionContextPaths 约定作用域字段从 context 快照的哪个路径读取,默认:

字段 默认路径
DeviceId device.cnc.deviceId
ToolNo business.tool.number
ToolType business.tool.type
ProcessId business.process.id
State business.machine.state

路径不存在时字段为 null,对应作用域限制不命中;需要时可改用条件引用。

9. 线程与生命周期

  • DecisionEngine 线程安全:Plan / Enqueue / Notify / Tick / Cancel 可并发调用;
  • Ready / Closed 在锁外触发,宿主回调里可以做 I/O;
  • 回调里的异常会被引擎吞掉并记录到 Snapshot().LastError,不打断其他意图;
  • 实例建议单例;规则通过 UpdateRules 热替换;
  • 引擎不持有定时器:Tick 的周期由宿主决定。

10. 扩展与限制

可以扩展的点:

  • 新数据源:实现 IDecisionValueSource,在 TryGet 里按前缀分派;
  • 新触发器:继承 DecisionTrigger 并扩展 DecisionTriggerJsonConverter(目前是封闭集合);
  • 宿主自定义去重:用 DecisionIntentQueue.FindByDedupe 或在落库层做。

当前限制:

  • 不做持久化、不做派发、不做重试计时;
  • 不读业务进程私有 context,只有宿主随调用 / 事件带过来的快照;
  • 规则里不做表达式运算,复杂判断先落成 biz:// 变量;
  • 重启恢复、去重一致性依赖宿主的等待记录。

依赖与版本

项 值
目标框架 net8.0
依赖 OpenRobot.Edge.Common
版本 0.1.0
dotnet build common/OpenRobot.Edge.Decision/OpenRobot.Edge.Decision.csproj
dotnet test test/OpenRobot.Edge.Decision.Tests/OpenRobot.Edge.Decision.Tests.csproj
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0 90 11/20/2026