Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaImportedConditionKeyTests.cs
T
Joseph Doherty d3067ca036 fix(dcl): key OPC UA alarms on ConditionId (#147)
OtOpcUa now exposes conditions imported over gRPC data connections in the
namespace https://zb.com/otopcua/mapped/conditions. Their ConditionId is
an opaque c1. NodeId stable for the life of the connection, but their
SourceName (<anchor>/<placement path>) moves when the primary placement
mapping changes. ScadaBridge keyed every condition on
SourceName.ConditionName, so a mapping change read as one alarm clearing
and a new one raising.

- Event filter selects ConditionId (select clause 19: ConditionType,
  empty browse path, AttributeId = NodeId).
- When the ConditionId (or SourceNode, which OtOpcUa sets to it) is in the
  mapped/conditions namespace, the per-condition key is its durable
  nsu=... string (index-proof across an OtOpcUa pair / upgrade). Every
  other OPC UA condition keeps the SourceName.ConditionName key, so no
  existing persisted row, MES script or operator view is re-keyed.
- The old SourceName.ConditionName text becomes an additive, display-only
  DisplayName: NativeAlarmTransition -> AlarmStateChanged ->
  AlarmStateUpdate.display_name (26) / DebugAlarmStateDto.display_name
  (22) -> ScriptAlarm.DisplayName. Persisted in native_alarm_state
  metadata_json (no column, no CDC trigger change); updates in place on
  every transition under the fixed key. Protos regenerated.
- Alarm Summary and Debug View show DisplayName (key as tooltip) and
  filter on it; site event log writes "label [key]".
- Upgrade: a pre-#147 row for an imported condition is retired by the
  first completed refresh snapshot (one return-to-normal + drop), then the
  condition continues under its ConditionId.

Tests: RealOpcUaImportedConditionKeyTests, OpcUaAlarmMapperTests,
NativeAlarmActorTests (DisplayName, rehydration, legacy-row retirement),
StreamRelayActorTests, SiteCommand golden sample, AlarmsAccessorTests,
DebugTreeBuilderTests; filter select-clause count 19 -> 20.
Docs: Component-DataConnectionLayer/Commons/Communication/SiteRuntime.
2026-11-28 09:14:49 -05:00

163 lines
7.4 KiB
C#

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;
/// <summary>
/// Gitea #147: OtOpcUa imported conditions (namespace <c>https://zb.com/otopcua/mapped/conditions</c>)
/// carry an opaque ConditionId stable for the life of the data connection, while their SourceName
/// moves with the server's mapping. <c>HandleAlarmEvent</c> must key them on the durable
/// ConditionId and carry <c>SourceName.ConditionName</c> as a display label only; every other
/// condition keeps the pre-#147 key.
/// </summary>
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)!;
/// <summary>A consumer OtOpcUa namespace table with the conditions namespace at <paramref name="conditionsIndex"/>.</summary>
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<string, Dictionary<string, (bool Active, bool Acked)>>)field.GetValue(client)!;
map[Handle] = new Dictionary<string, (bool Active, bool Acked)>(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<NativeAlarmTransition>();
Handler.Invoke(client, [Handle, Binding, new EventFieldList { EventFields = fields },
(Action<NativeAlarmTransition>)sink.Add]);
return Assert.Single(sink);
}
/// <summary>The imported condition is keyed on the durable ConditionId; the SourceName path is the label.</summary>
[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);
}
/// <summary>
/// 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).
/// </summary>
[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);
}
/// <summary>
/// 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.
/// </summary>
[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);
}
/// <summary>
/// A server that leaves the ConditionId operand unanswered still keys imported conditions on
/// SourceNode, which OtOpcUa sets to the ConditionId for them.
/// </summary>
[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);
}
/// <summary>
/// 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.
/// </summary>
[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);
}
/// <summary>With no namespace table at all nothing can be recognised as imported: legacy keying.</summary>
[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);
}
}