using System.Collections.Concurrent;
using System.Reflection;
using Opc.Ua;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters;
///
/// Gitea #147: OtOpcUa imported conditions (namespace https://zb.com/otopcua/mapped/conditions)
/// carry an opaque ConditionId stable for the life of the data connection, while their SourceName
/// moves with the server's mapping. HandleAlarmEvent must key them on the durable
/// ConditionId and carry SourceName.ConditionName as a display label only; every other
/// condition keeps the pre-#147 key.
///
public class RealOpcUaImportedConditionKeyTests
{
private const string Handle = "h1";
private const string Binding = "nsu=https://zb.com/otopcua/mapped/uns;s=assembly";
private const string ConditionsUri = "https://zb.com/otopcua/mapped/conditions";
private const string ConditionIdentifier = "c1.eyJDb25uZWN0aW9uSWQiOiJjb25uLTEiLCJDb25kaXRpb25LZXkiOiJrMSJ9";
private const string ExpectedKey = "nsu=" + ConditionsUri + ";s=" + ConditionIdentifier;
private static readonly MethodInfo Handler =
typeof(RealOpcUaClient).GetMethod("HandleAlarmEvent", BindingFlags.Instance | BindingFlags.NonPublic)!;
/// A consumer OtOpcUa namespace table with the conditions namespace at .
private static NamespaceTable Table(ushort conditionsIndex)
{
var t = new NamespaceTable();
t.Append("urn:localhost:OtOpcUa");
var others = new[] { "https://zb.com/otopcua/mapped/raw", "https://zb.com/otopcua/mapped/uns", "https://zb.com/otopcua/raw" };
var next = 0;
for (ushort i = 2; i <= 5; i++)
t.Append(i == conditionsIndex ? ConditionsUri : others[next++ % others.Length] + "/" + i);
return t;
}
private static RealOpcUaClient Client(ushort conditionsIndex = 4)
{
var client = new RealOpcUaClient { NamespaceUrisOverride = Table(conditionsIndex) };
var field = typeof(RealOpcUaClient).GetField("_alarmLastState", BindingFlags.Instance | BindingFlags.NonPublic)!;
var map = (ConcurrentDictionary>)field.GetValue(client)!;
map[Handle] = new Dictionary(StringComparer.Ordinal);
return client;
}
private static NativeAlarmTransition Emit(
RealOpcUaClient client, NodeId sourceNode, string sourceName, bool active, bool acked,
NodeId? conditionId, string conditionName = "HR200")
{
var fields = new Variant[20];
fields[0] = Variant.From(ObjectTypeIds.OffNormalAlarmType);
fields[1] = Variant.From(sourceNode);
fields[2] = Variant.From(sourceName);
fields[3] = Variant.From(DateTime.UtcNow);
fields[4] = Variant.From(new LocalizedText("msg"));
fields[5] = Variant.From((ushort)500);
fields[6] = Variant.From(active);
fields[7] = Variant.From(acked);
fields[11] = Variant.From(conditionName);
if (conditionId is { } id)
fields[19] = Variant.From(id);
var sink = new List();
Handler.Invoke(client, [Handle, Binding, new EventFieldList { EventFields = fields },
(Action)sink.Add]);
return Assert.Single(sink);
}
/// The imported condition is keyed on the durable ConditionId; the SourceName path is the label.
[Fact]
public void ImportedCondition_IsKeyedOnDurableConditionId()
{
var client = Client();
var id = new NodeId(ConditionIdentifier, 4);
var t = Emit(client, id, "Plant/remote-a/Modbus/dev1/HR200", active: true, acked: false, conditionId: id);
Assert.Equal(ExpectedKey, t.SourceReference);
Assert.Equal("Plant/remote-a/Modbus/dev1/HR200.HR200", t.DisplayName);
Assert.Equal(Binding, t.SourceObjectReference); // routing identity unchanged
Assert.Equal(AlarmTransitionKind.Raise, t.Kind);
}
///
/// A primary-placement change moves SourceName: the key holds, the label updates in place, and
/// the transition kind is derived against the SAME condition's prior state (an ack after the move
/// is an Acknowledge, not a fresh Raise of a "new" alarm).
///
[Fact]
public void SourceNameMove_KeepsKey_UpdatesLabel_AndKindContinuity()
{
var client = Client();
var id = new NodeId(ConditionIdentifier, 4);
var raised = Emit(client, id, "Plant/remote-a/Modbus/dev1/HR200", active: true, acked: false, conditionId: id);
var acked = Emit(client, id, "assembly/remote-line-2/filler/HR200", active: true, acked: true, conditionId: id);
Assert.Equal(raised.SourceReference, acked.SourceReference);
Assert.Equal("assembly/remote-line-2/filler/HR200.HR200", acked.DisplayName);
Assert.Equal(AlarmTransitionKind.Acknowledge, acked.Kind);
}
///
/// The key is namespace-index-proof: two servers (an OtOpcUa pair) or one server after an upgrade
/// may place the conditions namespace at different indices; the key must not change on failover.
///
[Fact]
public void Key_IsIndependentOfTheNamespaceIndex()
{
var a = Emit(Client(conditionsIndex: 3), new NodeId(ConditionIdentifier, 3), "x", true, false, new NodeId(ConditionIdentifier, 3));
var b = Emit(Client(conditionsIndex: 5), new NodeId(ConditionIdentifier, 5), "x", true, false, new NodeId(ConditionIdentifier, 5));
Assert.Equal(ExpectedKey, a.SourceReference);
Assert.Equal(a.SourceReference, b.SourceReference);
}
///
/// A server that leaves the ConditionId operand unanswered still keys imported conditions on
/// SourceNode, which OtOpcUa sets to the ConditionId for them.
///
[Fact]
public void MissingConditionIdOperand_FallsBackToSourceNode()
{
var t = Emit(Client(), new NodeId(ConditionIdentifier, 4), "Plant/remote-a/HR200", true, false, conditionId: null);
Assert.Equal(ExpectedKey, t.SourceReference);
Assert.Equal("Plant/remote-a/HR200.HR200", t.DisplayName);
}
///
/// A local OtOpcUa (or any third-party) condition keeps the pre-#147 SourceName.ConditionName key
/// and no label, even when the server answers ConditionId — so no persisted row is re-keyed.
///
[Fact]
public void NonImportedCondition_KeepsLegacyKey()
{
// Index 2 is a mapped/raw namespace in this table, not the conditions namespace.
var local = new NodeId("pymodbus/plc/HR200", 2);
var t = Emit(Client(), local, "pymodbus/plc/HR200", true, false, conditionId: local);
Assert.Equal("pymodbus/plc/HR200.HR200", t.SourceReference);
Assert.Null(t.DisplayName);
}
/// With no namespace table at all nothing can be recognised as imported: legacy keying.
[Fact]
public void NoNamespaceTable_KeepsLegacyKey()
{
var client = Client();
client.NamespaceUrisOverride = null;
var id = new NodeId(ConditionIdentifier, 4);
var t = Emit(client, id, "Plant/remote-a/HR200", true, false, conditionId: id);
Assert.Equal("Plant/remote-a/HR200.HR200", t.SourceReference);
Assert.Null(t.DisplayName);
}
}