Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/MTConnectConditionAlarmWireTests.cs
T
Joseph Doherty f4d513e111 test+docs(mtconnect): CONDITION alarm wire test, reinit barrier, docs (#626)
MTConnectConditionAlarmWireTests drives a scripted Agent's Fault/Normal through the real
driver, NativeAlarmProjector and sink to a client event subscription on the raw device
folder. docs/drivers/MTConnect.md replaces 'CONDITION v1: plain String' with the alarm
mapping, opt-in authoring, multi-condition, ack, replay and comms-loss behaviour, and a
live-check recipe; EVENT vocabularies as enumerations marked won't-fix. AlarmTracking.md
lists the MTConnect source and the two new AlarmEventArgs fields.

Claude-Session: https://claude.ai/code/session_01Ef2ozxS7QPanGT8uoATbTe
2026-10-08 15:13:30 -04:00

132 lines
6.0 KiB
C#

using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.MTConnect;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// Gitea #626 over the wire — an MTConnect CONDITION transition, streamed by a scripted Agent through the real
/// <see cref="MTConnectDriver"/>, projected by the production <see cref="NativeAlarmProjector"/> and written
/// through the production sink, reaches a client's event subscription on the RAW DEVICE FOLDER as a Part 9
/// condition event carrying the driver's message — then its return to normal does too.
/// </summary>
/// <remarks>
/// The one seam not exercised is <c>DriverHostActor</c>'s routing (ConditionId → condition NodeId), which
/// <c>DriverHostActorNativeAlarmTests</c> covers; here the driver's ConditionId is asserted to BE the
/// materialised condition's RawPath, which is the whole contract that routing relies on.
/// </remarks>
public sealed class MTConnectConditionAlarmWireTests
{
private const string DataItemId = "dev1_system_cond";
[Fact]
public async Task A_condition_fault_and_its_clear_reach_the_raw_device_folder_as_part9_events()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("MTConnectConditionWire", encrypted: false, ct);
try
{
rig.MaterialiseNative();
using var session = await rig.ConnectAsync(anonymous: true, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var rawNs = (ushort)session.NamespaceUris.GetIndex(V3NodeIds.RawNamespaceUri);
var folderItem = RecordedEvents.AddEventItem(subscription, new NodeId(RawDeviceFolder, rawNs));
await subscription.ApplyChangesAsync(ct);
folderItem.Status.Error.ShouldBeNull();
var agent = new ScriptedAgent();
var driver = new MTConnectDriver(
new ZB.MOM.WW.OtOpcUa.Driver.MTConnect.MTConnectDriverOptions
{
AgentUri = "http://scripted-agent:5000",
RawTags = [new RawTagEntry(RawAlarmPath, $$"""{"address":"{{DataItemId}}"}""", false, "dev1")],
},
"mt-wire",
_ => agent);
// What DriverHostActor.ForwardNativeAlarm does for a routed transition, minus the routing.
var projector = new NativeAlarmProjector();
var routed = new List<string>();
driver.OnAlarmEvent += (_, e) =>
{
lock (routed) routed.Add(e.ConditionId);
rig.Sink.WriteAlarmCondition(e.ConditionId, projector.Project(e.ConditionId, e), e.SourceTimestampUtc, AddressSpaceRealm.Raw);
};
await driver.InitializeAsync("{}", ct);
await driver.SubscribeAlarmsAsync([RawAlarmPath], ct);
agent.Push(Condition("Fault", "E17", "Spindle overtemperature", 108));
const string FaultMessage = "Spindle overtemperature [nativeCode=E17]";
await RecordedEvents.WaitUntilAsync(() => events.Has(folderItem, FaultMessage));
agent.Push(Condition("Normal", null, null, 109));
await RecordedEvents.WaitUntilAsync(() => events.Has(folderItem, "SYSTEM Normal"));
lock (routed) routed.ShouldAllBe(id => id == RawAlarmPath, "ConditionId must be the alarm tag's RawPath");
var fault = events.ConditionEvents(folderItem, FaultMessage).ShouldHaveSingleItem();
fault[RecordedEvents.AckedField].Value.ShouldBe(false, "a fresh fault is unacknowledged");
await driver.ShutdownAsync(ct);
}
finally
{
await rig.DisposeAsync();
}
}
private static MTConnectStreamsResult Condition(string state, string? nativeCode, string? text, long sequence) =>
new(1, sequence + 1, sequence,
[
new MTConnectObservation(DataItemId, state, DateTime.UtcNow,
Condition: new MTConnectConditionDetail(text, nativeCode, null, null, "SYSTEM")),
]);
/// <summary>An Agent whose <c>/current</c> reports the condition Normal and whose <c>/sample</c> a test drives.</summary>
private sealed class ScriptedAgent : IMTConnectAgentClient
{
private readonly Channel<MTConnectStreamsResult> _chunks = Channel.CreateUnbounded<MTConnectStreamsResult>();
public void Push(MTConnectStreamsResult chunk) => _chunks.Writer.TryWrite(chunk);
public Task<MTConnectProbeModel> ProbeAsync(CancellationToken ct) =>
Task.FromResult(new MTConnectProbeModel(
[
new MTConnectDevice("dev1", "dev1", [],
[new MTConnectDataItem(DataItemId, "system", "CONDITION", "SYSTEM", null, null, null, null)]),
]));
public Task<MTConnectStreamsResult> CurrentAsync(CancellationToken ct) =>
Task.FromResult(new MTConnectStreamsResult(1, 108, 1,
[
new MTConnectObservation(DataItemId, "Normal", DateTime.UtcNow,
Condition: new MTConnectConditionDetail(null, null, null, null, "SYSTEM")),
]));
public async IAsyncEnumerable<MTConnectStreamsResult> SampleAsync(
long from, [EnumeratorCancellation] CancellationToken ct)
{
while (true)
{
yield return await _chunks.Reader.ReadAsync(ct);
}
}
public Task<MTConnectWriteOutcome> WriteObservationAsync(
string deviceName, string dataItemId, string value, CancellationToken cancellationToken) =>
throw new NotSupportedException();
public void Dispose() => _chunks.Writer.TryComplete();
}
}