239 lines
10 KiB
C#
239 lines
10 KiB
C#
using Opc.Ua;
|
|
using Opc.Ua.Client;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
|
|
|
|
/// <summary>
|
|
/// grpc-data A1 (§5.1 OpcUaClient row): the driver raises
|
|
/// <see cref="IAlarmInitialStateSignal.InitialAlarmStateDelivered"/> on the subscription's
|
|
/// <c>RefreshEndEventType</c> — on the event route, after the refreshed events before it (F1) — never when
|
|
/// ConditionRefresh returns; an upstream without ConditionRefresh reports <c>Unsignalable</c> (vi); the alarm
|
|
/// subscription publishes sequentially (G2).
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
[Trait("Feature", "GrpcData")]
|
|
[Trait("Phase", "A1")]
|
|
public sealed class OpcUaClientInitialAlarmStateSignalTests
|
|
{
|
|
private const string Trip1 = "Plant/opc/plc/Trip1";
|
|
|
|
/// <summary>
|
|
/// (iii) F1: the refresh call has returned but the refreshed events arrive later; nothing is signalled until
|
|
/// the RefreshEnd, which follows the refreshed Active event on the same route.
|
|
/// </summary>
|
|
[Fact]
|
|
public void Known_only_on_RefreshEnd_after_the_refreshed_events()
|
|
{
|
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-f1");
|
|
var trace = Record(drv);
|
|
var handle = drv.AddAlarmSubscriptionForTest([Trip1]);
|
|
var index = new Dictionary<string, string> { ["ns=3;s=Alarms.Trip1"] = Trip1 };
|
|
|
|
// ConditionRefreshAsync "returned" here — and nothing was signalled for it.
|
|
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshStartEventType), index, handle);
|
|
trace.ShouldBeEmpty();
|
|
drv.RouteAlarmEvent(Condition(active: true, acked: false), index, handle);
|
|
trace.ShouldBe(["event:" + Trip1 + ":Retrigger"]);
|
|
|
|
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, handle);
|
|
trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]);
|
|
}
|
|
|
|
/// <summary>A RefreshEnd for a subscription that was released (no live alarm subscription, G5) signals nothing.</summary>
|
|
[Fact]
|
|
public void RefreshEnd_of_a_released_subscription_signals_nothing()
|
|
{
|
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-g5");
|
|
var trace = Record(drv);
|
|
var live = drv.AddAlarmSubscriptionForTest([Trip1]);
|
|
var index = new Dictionary<string, string>();
|
|
|
|
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, new StrayHandle());
|
|
trace.ShouldBeEmpty();
|
|
// Positive control: the live subscription's RefreshEnd does signal.
|
|
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, live);
|
|
trace.ShouldBe(["signal:" + Trip1]);
|
|
}
|
|
|
|
/// <summary>(vi) an upstream without ConditionRefresh reports the subscription's refs unsignalable (backstop).</summary>
|
|
[Fact]
|
|
public void Unsupported_ConditionRefresh_reports_the_refs_unsignalable()
|
|
{
|
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-backstop");
|
|
var raised = new List<AlarmInitialStateEventArgs>();
|
|
drv.InitialAlarmStateDelivered += (_, e) => raised.Add(e);
|
|
var handle = drv.AddAlarmSubscriptionForTest([Trip1, "Plant/opc/plc/Trip2"]);
|
|
|
|
drv.ReportRefreshUnsupportedForTest(handle);
|
|
|
|
raised.ShouldHaveSingleItem();
|
|
raised[0].Unsignalable.ShouldBeTrue();
|
|
raised[0].ConditionIds.ShouldBe([Trip1, "Plant/opc/plc/Trip2"]);
|
|
}
|
|
|
|
/// <summary>(ix) G2 configuration pin: the alarm subscription publishes sequentially; data subscriptions untouched.</summary>
|
|
[Fact]
|
|
public void Alarm_subscription_sets_SequentialPublishing()
|
|
{
|
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-g2-pin");
|
|
var options = drv.BuildAlarmSubscriptionOptions(7);
|
|
options.SequentialPublishing.ShouldBeTrue();
|
|
options.DisplayName.ShouldEndWith("7");
|
|
}
|
|
|
|
/// <summary>
|
|
/// (ix) G2: a refresh replay split across two publish responses that ARRIVE out of order (seq 2 = RefreshEnd
|
|
/// before seq 1 = the refreshed Active event). Through the real SDK subscription with the driver's alarm
|
|
/// options, the event route still sees the refreshed event first and the RefreshEnd last.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Out_of_order_publish_responses_route_the_RefreshEnd_last()
|
|
{
|
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-g2");
|
|
var trace = Record(drv);
|
|
var handle = drv.AddAlarmSubscriptionForTest([Trip1]);
|
|
var index = new Dictionary<string, string> { ["ns=3;s=Alarms.Trip1"] = Trip1 };
|
|
|
|
var replay = await SdkReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1),
|
|
[(2u, Marker(ObjectTypeIds.RefreshEndEventType)), (1u, Condition(active: true, acked: false))],
|
|
fields => drv.RouteAlarmEvent(fields, index, handle));
|
|
|
|
replay.ShouldBe([1u, 2u], "the SDK processed the publish responses in sequence-number order");
|
|
trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]);
|
|
}
|
|
|
|
private static List<string> Record(OpcUaClientDriver drv)
|
|
{
|
|
var trace = new List<string>();
|
|
drv.OnAlarmEvent += (_, e) => { lock (trace) trace.Add($"event:{e.ConditionId}:{e.Kind}"); };
|
|
drv.InitialAlarmStateDelivered += (_, e) =>
|
|
{
|
|
lock (trace) trace.Add("signal:" + string.Join(',', e.ConditionIds));
|
|
};
|
|
return trace;
|
|
}
|
|
|
|
private static List<Variant> Marker(NodeId type) =>
|
|
[
|
|
Variant.From(new byte[] { 9 }.ToByteString()),
|
|
new Variant(type),
|
|
new Variant(ObjectIds.Server),
|
|
new Variant(new LocalizedText("refresh")),
|
|
new Variant((ushort)100),
|
|
new Variant(DateTime.UtcNow),
|
|
Variant.Null,
|
|
Variant.Null,
|
|
Variant.Null,
|
|
Variant.Null,
|
|
];
|
|
|
|
private static List<Variant> Condition(bool active, bool acked) =>
|
|
[
|
|
Variant.From(new byte[] { 1 }.ToByteString()),
|
|
new Variant(new NodeId("TripAlarmType", 3)),
|
|
new Variant(NodeId.Parse("ns=3;s=Alarms.Trip1")),
|
|
new Variant(new LocalizedText("tripped")),
|
|
new Variant((ushort)700),
|
|
new Variant(DateTime.UtcNow),
|
|
new Variant(NodeId.Parse("ns=3;s=Alarms.Trip1.Cond")),
|
|
new Variant(active),
|
|
new Variant(acked),
|
|
Variant.Null,
|
|
];
|
|
|
|
private sealed class StrayHandle : IAlarmSubscriptionHandle
|
|
{
|
|
public string DiagnosticId => "stray";
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Feeds notification messages into a REAL SDK <see cref="Subscription"/> (no session) through its internal
|
|
/// publish-response cache, in the given arrival order, and records the order the SDK's message worker
|
|
/// delivered them to the event monitored item.
|
|
/// </summary>
|
|
internal static class SdkReplay
|
|
{
|
|
public static async Task<List<uint>> DeliverAsync(
|
|
SubscriptionOptions options, IReadOnlyList<(uint Seq, List<Variant> Fields)> arrivals, Action<List<Variant>> route)
|
|
{
|
|
var delivered = new List<uint>();
|
|
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var subscription = new Subscription(telemetry: null!, options);
|
|
var item = new MonitoredItem(telemetry: null!, new MonitoredItemOptions
|
|
{
|
|
DisplayName = "Server/Events",
|
|
StartNodeId = ObjectIds.Server,
|
|
AttributeId = Attributes.EventNotifier,
|
|
Filter = new EventFilter(),
|
|
});
|
|
item.Notification += (_, args) =>
|
|
{
|
|
if (args.NotificationValue is not EventFieldList efl) return;
|
|
var fields = efl.EventFields.ToList();
|
|
var seq = OpcUaClientDriver.IsRefreshEnd(fields) ? 2u : 1u; // the test's two messages, by content
|
|
lock (delivered)
|
|
{
|
|
delivered.Add(seq);
|
|
route(fields);
|
|
if (delivered.Count == arrivals.Count) done.TrySetResult();
|
|
}
|
|
};
|
|
subscription.AddItem(item);
|
|
|
|
var save = typeof(Subscription).GetMethods(
|
|
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public |
|
|
System.Reflection.BindingFlags.NonPublic)
|
|
.FirstOrDefault(m => m.Name == "SaveMessageInCache" && m.GetParameters().Length == 2)
|
|
?? throw new InvalidOperationException("SDK Subscription.SaveMessageInCache not found");
|
|
// The message worker is started with the keep-alive timer (normally by Create/Transfer on a live session).
|
|
var startWorker = typeof(Subscription).GetMethod("StartKeepAliveTimer",
|
|
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
|
|
?? throw new InvalidOperationException("SDK Subscription.StartKeepAliveTimer not found");
|
|
startWorker.Invoke(subscription, null);
|
|
var available = arrivals.Select(a => a.Seq).OrderBy(s => s).ToArray();
|
|
foreach (var (seq, fields) in arrivals)
|
|
{
|
|
var message = new NotificationMessage
|
|
{
|
|
SequenceNumber = seq,
|
|
PublishTime = DateTime.UtcNow,
|
|
NotificationData =
|
|
[
|
|
new ExtensionObject(new EventNotificationList
|
|
{
|
|
Events = [new EventFieldList { ClientHandle = item.ClientHandle, EventFields = fields.ToArray() }],
|
|
}),
|
|
],
|
|
};
|
|
save.Invoke(subscription, [ToParam(save, available), message]);
|
|
// Let the message worker run on the early arrival before the next one lands — a real gap between
|
|
// two publish responses, so a non-sequential worker would process the later sequence number first.
|
|
await Task.Delay(300);
|
|
}
|
|
|
|
try
|
|
{
|
|
await done.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
|
}
|
|
finally
|
|
{
|
|
subscription.Dispose();
|
|
}
|
|
|
|
return delivered;
|
|
}
|
|
|
|
private static object ToParam(System.Reflection.MethodInfo save, uint[] available)
|
|
{
|
|
var t = save.GetParameters()[0].ParameterType;
|
|
if (t.IsInstanceOfType(available)) return available;
|
|
var implicitOp = t.GetMethods().FirstOrDefault(m => m.Name == "op_Implicit" && m.ReturnType == t
|
|
&& m.GetParameters()[0].ParameterType == typeof(uint[]));
|
|
return implicitOp?.Invoke(null, [available]) ?? Activator.CreateInstance(t, available)!;
|
|
}
|
|
}
|