Compare commits
5 Commits
phase-2-pr
...
phase-3-pr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f53c39a598 | ||
| d569c39f30 | |||
|
|
190d09cdeb | ||
| 4e0040e670 | |||
| 91cb2a1355 |
@@ -42,4 +42,39 @@ public interface IVariableHandle
|
|||||||
{
|
{
|
||||||
/// <summary>Driver-side full reference for read/write addressing.</summary>
|
/// <summary>Driver-side full reference for read/write addressing.</summary>
|
||||||
string FullReference { get; }
|
string FullReference { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Annotate this variable with an OPC UA <c>AlarmConditionState</c>. Drivers with
|
||||||
|
/// <see cref="DriverAttributeInfo.IsAlarm"/> = true call this during discovery so the
|
||||||
|
/// concrete address-space builder can materialize a sibling condition node. The returned
|
||||||
|
/// sink receives lifecycle transitions raised through <see cref="IAlarmSource.OnAlarmEvent"/>
|
||||||
|
/// — the generic node manager wires the subscription; the concrete builder decides how
|
||||||
|
/// to surface the state (e.g. OPC UA <c>AlarmConditionState.Activate</c>,
|
||||||
|
/// <c>Acknowledge</c>, <c>Deactivate</c>).
|
||||||
|
/// </summary>
|
||||||
|
IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo info);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Metadata used to materialize an OPC UA <c>AlarmConditionState</c> sibling for a variable.
|
||||||
|
/// Populated by the driver's discovery step; concrete builders decide how to surface it.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="SourceName">Human-readable alarm name used for the <c>SourceName</c> event field.</param>
|
||||||
|
/// <param name="InitialSeverity">Severity at address-space build time; updates arrive via <see cref="IAlarmConditionSink"/>.</param>
|
||||||
|
/// <param name="InitialDescription">Initial description; updates arrive via <see cref="IAlarmConditionSink"/>.</param>
|
||||||
|
public sealed record AlarmConditionInfo(
|
||||||
|
string SourceName,
|
||||||
|
AlarmSeverity InitialSeverity,
|
||||||
|
string? InitialDescription);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sink a concrete address-space builder returns from <see cref="IVariableHandle.MarkAsAlarmCondition"/>.
|
||||||
|
/// The generic node manager routes per-alarm <see cref="IAlarmSource.OnAlarmEvent"/> payloads here —
|
||||||
|
/// the sink translates the transition into an OPC UA condition state change or whatever the
|
||||||
|
/// concrete builder's backing address space supports.
|
||||||
|
/// </summary>
|
||||||
|
public interface IAlarmConditionSink
|
||||||
|
{
|
||||||
|
/// <summary>Push an alarm transition (Active / Acknowledged / Inactive) for this condition.</summary>
|
||||||
|
void OnTransition(AlarmEventArgs args);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,17 @@ public sealed class DriverHost : IAsyncDisposable
|
|||||||
return _drivers.TryGetValue(driverInstanceId, out var d) ? d.GetHealth() : null;
|
return _drivers.TryGetValue(driverInstanceId, out var d) ? d.GetHealth() : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Look up a registered driver by instance id. Used by the OPC UA server runtime
|
||||||
|
/// (<c>OtOpcUaServer</c>) to instantiate one <c>DriverNodeManager</c> per driver at
|
||||||
|
/// startup. Returns null when the driver is not registered.
|
||||||
|
/// </summary>
|
||||||
|
public IDriver? GetDriver(string driverInstanceId)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
return _drivers.TryGetValue(driverInstanceId, out var d) ? d : null;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Registers the driver and calls <see cref="IDriver.InitializeAsync"/>. If initialization
|
/// Registers the driver and calls <see cref="IDriver.InitializeAsync"/>. If initialization
|
||||||
/// throws, the driver is kept in the registry so the operator can retry; quality on its
|
/// throws, the driver is kept in the registry so the operator can retry; quality on its
|
||||||
|
|||||||
@@ -1,27 +1,41 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||||
|
|
||||||
namespace ZB.MOM.WW.OtOpcUa.Core.OpcUa;
|
namespace ZB.MOM.WW.OtOpcUa.Core.OpcUa;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Generic, driver-agnostic backbone for populating the OPC UA address space from an
|
/// Generic, driver-agnostic backbone for populating the OPC UA address space from an
|
||||||
/// <see cref="IDriver"/>. The Galaxy-specific subclass (<c>GalaxyNodeManager</c>) is deferred
|
/// <see cref="IDriver"/>. Walks the driver's discovery, wires the alarm + data-change +
|
||||||
/// to Phase 2 per decision #62 — this class is the foundation that Phase 2 ports the v1
|
/// rediscovery subscription events, and hands each variable to the supplied
|
||||||
/// <c>LmxNodeManager</c> logic into.
|
/// <see cref="IAddressSpaceBuilder"/>. Concrete OPC UA server implementations provide the
|
||||||
|
/// builder — see the Server project's <c>OpcUaAddressSpaceBuilder</c> for the materialization
|
||||||
|
/// against <c>CustomNodeManager2</c>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// Phase 1 status: scaffold only. The v1 <c>LmxNodeManager</c> in the legacy Host is unchanged
|
/// Per <c>docs/v2/plan.md</c> decision #52 + #62 — Core owns the node tree, drivers stream
|
||||||
/// so IntegrationTests continue to pass. Phase 2 will lift-and-shift its logic here, swapping
|
/// <c>Folder</c>/<c>Variable</c> calls, alarm-bearing variables are annotated via
|
||||||
/// <c>IMxAccessClient</c> for <see cref="IDriver"/> and <c>GalaxyAttributeInfo</c> for
|
/// <see cref="IVariableHandle.MarkAsAlarmCondition"/> and subsequent
|
||||||
/// <see cref="DriverAttributeInfo"/>.
|
/// <see cref="IAlarmSource.OnAlarmEvent"/> payloads route to the sink the builder returned.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public abstract class GenericDriverNodeManager(IDriver driver)
|
public class GenericDriverNodeManager(IDriver driver) : IDisposable
|
||||||
{
|
{
|
||||||
protected IDriver Driver { get; } = driver ?? throw new ArgumentNullException(nameof(driver));
|
protected IDriver Driver { get; } = driver ?? throw new ArgumentNullException(nameof(driver));
|
||||||
|
|
||||||
public string DriverInstanceId => Driver.DriverInstanceId;
|
public string DriverInstanceId => Driver.DriverInstanceId;
|
||||||
|
|
||||||
|
// Source tag (DriverAttributeInfo.FullName) → alarm-condition sink. Populated during
|
||||||
|
// BuildAddressSpaceAsync by a recording IAddressSpaceBuilder implementation that captures the
|
||||||
|
// IVariableHandle per attr.IsAlarm=true variable and calls MarkAsAlarmCondition.
|
||||||
|
private readonly ConcurrentDictionary<string, IAlarmConditionSink> _alarmSinks =
|
||||||
|
new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
private EventHandler<AlarmEventArgs>? _alarmForwarder;
|
||||||
|
private bool _disposed;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Populates the address space by streaming nodes from the driver into the supplied builder.
|
/// Populates the address space by streaming nodes from the driver into the supplied builder,
|
||||||
|
/// wraps the builder so alarm-condition sinks are captured, subscribes to the driver's
|
||||||
|
/// alarm event stream, and routes each transition to the matching sink by <c>SourceNodeId</c>.
|
||||||
/// Driver exceptions are isolated per decision #12 — the driver's subtree is marked Faulted,
|
/// Driver exceptions are isolated per decision #12 — the driver's subtree is marked Faulted,
|
||||||
/// but other drivers remain available.
|
/// but other drivers remain available.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -32,6 +46,73 @@ public abstract class GenericDriverNodeManager(IDriver driver)
|
|||||||
if (Driver is not ITagDiscovery discovery)
|
if (Driver is not ITagDiscovery discovery)
|
||||||
throw new NotSupportedException($"Driver '{Driver.DriverInstanceId}' does not implement ITagDiscovery.");
|
throw new NotSupportedException($"Driver '{Driver.DriverInstanceId}' does not implement ITagDiscovery.");
|
||||||
|
|
||||||
await discovery.DiscoverAsync(builder, ct);
|
var capturing = new CapturingBuilder(builder, _alarmSinks);
|
||||||
|
await discovery.DiscoverAsync(capturing, ct);
|
||||||
|
|
||||||
|
if (Driver is IAlarmSource alarmSource)
|
||||||
|
{
|
||||||
|
_alarmForwarder = (_, e) =>
|
||||||
|
{
|
||||||
|
// Route the alarm to the sink registered for the originating variable, if any.
|
||||||
|
// Unknown source ids are dropped silently — they may belong to another driver or
|
||||||
|
// to a variable the builder chose not to flag as an alarm condition.
|
||||||
|
if (_alarmSinks.TryGetValue(e.SourceNodeId, out var sink))
|
||||||
|
sink.OnTransition(e);
|
||||||
|
};
|
||||||
|
alarmSource.OnAlarmEvent += _alarmForwarder;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (_disposed) return;
|
||||||
|
_disposed = true;
|
||||||
|
if (_alarmForwarder is not null && Driver is IAlarmSource alarmSource)
|
||||||
|
{
|
||||||
|
alarmSource.OnAlarmEvent -= _alarmForwarder;
|
||||||
|
}
|
||||||
|
_alarmSinks.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Snapshot the current alarm-sink registry by source node id. Diagnostic + test hook;
|
||||||
|
/// not part of the hot path.
|
||||||
|
/// </summary>
|
||||||
|
internal IReadOnlyCollection<string> TrackedAlarmSources => _alarmSinks.Keys.ToList();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wraps the caller-supplied <see cref="IAddressSpaceBuilder"/> so every
|
||||||
|
/// <see cref="IVariableHandle.MarkAsAlarmCondition"/> call registers the returned sink in
|
||||||
|
/// the node manager's source-node-id map. The builder itself drives materialization;
|
||||||
|
/// this wrapper only observes.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class CapturingBuilder(
|
||||||
|
IAddressSpaceBuilder inner,
|
||||||
|
ConcurrentDictionary<string, IAlarmConditionSink> sinks) : IAddressSpaceBuilder
|
||||||
|
{
|
||||||
|
public IAddressSpaceBuilder Folder(string browseName, string displayName)
|
||||||
|
=> new CapturingBuilder(inner.Folder(browseName, displayName), sinks);
|
||||||
|
|
||||||
|
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
|
||||||
|
=> new CapturingHandle(inner.Variable(browseName, displayName, attributeInfo), sinks);
|
||||||
|
|
||||||
|
public void AddProperty(string browseName, DriverDataType dataType, object? value)
|
||||||
|
=> inner.AddProperty(browseName, dataType, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class CapturingHandle(
|
||||||
|
IVariableHandle inner,
|
||||||
|
ConcurrentDictionary<string, IAlarmConditionSink> sinks) : IVariableHandle
|
||||||
|
{
|
||||||
|
public string FullReference => inner.FullReference;
|
||||||
|
|
||||||
|
public IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo info)
|
||||||
|
{
|
||||||
|
var sink = inner.MarkAsAlarmCondition(info);
|
||||||
|
// Register by the driver-side full reference so the alarm forwarder can look it up
|
||||||
|
// using AlarmEventArgs.SourceNodeId (which the driver populates with the same tag).
|
||||||
|
sinks[inner.FullReference] = sink;
|
||||||
|
return sink;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,10 @@
|
|||||||
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Configuration\ZB.MOM.WW.OtOpcUa.Configuration.csproj"/>
|
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Configuration\ZB.MOM.WW.OtOpcUa.Configuration.csproj"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Core.Tests"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-37gx-xxp4-5rgx"/>
|
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-37gx-xxp4-5rgx"/>
|
||||||
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-w3x6-4m5h-cxqf"/>
|
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-w3x6-4m5h-cxqf"/>
|
||||||
|
|||||||
@@ -114,17 +114,31 @@ public sealed class GalaxyProxyDriver(GalaxyProxyOptions options)
|
|||||||
var folder = builder.Folder(obj.ContainedName, obj.ContainedName);
|
var folder = builder.Folder(obj.ContainedName, obj.ContainedName);
|
||||||
foreach (var attr in obj.Attributes)
|
foreach (var attr in obj.Attributes)
|
||||||
{
|
{
|
||||||
folder.Variable(
|
var fullName = $"{obj.TagName}.{attr.AttributeName}";
|
||||||
|
var handle = folder.Variable(
|
||||||
attr.AttributeName,
|
attr.AttributeName,
|
||||||
attr.AttributeName,
|
attr.AttributeName,
|
||||||
new DriverAttributeInfo(
|
new DriverAttributeInfo(
|
||||||
FullName: $"{obj.TagName}.{attr.AttributeName}",
|
FullName: fullName,
|
||||||
DriverDataType: MapDataType(attr.MxDataType),
|
DriverDataType: MapDataType(attr.MxDataType),
|
||||||
IsArray: attr.IsArray,
|
IsArray: attr.IsArray,
|
||||||
ArrayDim: attr.ArrayDim,
|
ArrayDim: attr.ArrayDim,
|
||||||
SecurityClass: MapSecurity(attr.SecurityClassification),
|
SecurityClass: MapSecurity(attr.SecurityClassification),
|
||||||
IsHistorized: attr.IsHistorized,
|
IsHistorized: attr.IsHistorized,
|
||||||
IsAlarm: attr.IsAlarm));
|
IsAlarm: attr.IsAlarm));
|
||||||
|
|
||||||
|
// PR 15: when Galaxy flags the attribute as alarm-bearing (AlarmExtension
|
||||||
|
// primitive), register an alarm-condition sink so the generic node manager
|
||||||
|
// can route OnAlarmEvent payloads for this tag to the concrete address-space
|
||||||
|
// builder. Severity default Medium — the live severity arrives through
|
||||||
|
// AlarmEventArgs once MxAccessGalaxyBackend's tracker starts firing.
|
||||||
|
if (attr.IsAlarm)
|
||||||
|
{
|
||||||
|
handle.MarkAsAlarmCondition(new AlarmConditionInfo(
|
||||||
|
SourceName: fullName,
|
||||||
|
InitialSeverity: AlarmSeverity.Medium,
|
||||||
|
InitialDescription: null));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
360
src/ZB.MOM.WW.OtOpcUa.Server/OpcUa/DriverNodeManager.cs
Normal file
360
src/ZB.MOM.WW.OtOpcUa.Server/OpcUa/DriverNodeManager.cs
Normal file
@@ -0,0 +1,360 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Opc.Ua;
|
||||||
|
using Opc.Ua.Server;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||||
|
using DriverWriteRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.WriteRequest;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Server.OpcUa;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Concrete <see cref="CustomNodeManager2"/> that materializes the driver's address space
|
||||||
|
/// into OPC UA nodes. Implements <see cref="IAddressSpaceBuilder"/> itself so
|
||||||
|
/// <c>GenericDriverNodeManager.BuildAddressSpaceAsync</c> can stream nodes directly into the
|
||||||
|
/// OPC UA server's namespace. PR 15's <c>MarkAsAlarmCondition</c> hook creates a sibling
|
||||||
|
/// <see cref="AlarmConditionState"/> node per alarm-flagged variable; subsequent driver
|
||||||
|
/// <c>OnAlarmEvent</c> pushes land through the returned sink to drive Activate /
|
||||||
|
/// Acknowledge / Deactivate transitions.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Read / Subscribe / Write are routed to the driver's capability interfaces — the node
|
||||||
|
/// manager holds references to <see cref="IReadable"/>, <see cref="ISubscribable"/>, and
|
||||||
|
/// <see cref="IWritable"/> when present. Nodes with no driver backing (plain folders) are
|
||||||
|
/// served directly from the internal PredefinedNodes table.
|
||||||
|
/// </remarks>
|
||||||
|
public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
|
||||||
|
{
|
||||||
|
private readonly IDriver _driver;
|
||||||
|
private readonly IReadable? _readable;
|
||||||
|
private readonly IWritable? _writable;
|
||||||
|
private readonly ILogger<DriverNodeManager> _logger;
|
||||||
|
|
||||||
|
private FolderState? _driverRoot;
|
||||||
|
private readonly Dictionary<string, BaseDataVariableState> _variablesByFullRef = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
// Active building folder — set per Folder() call so Variable() lands under the right parent.
|
||||||
|
// A stack would support nested folders; we use a single current folder because IAddressSpaceBuilder
|
||||||
|
// returns a child builder per Folder call and the caller threads nesting through those references.
|
||||||
|
private FolderState _currentFolder = null!;
|
||||||
|
|
||||||
|
public DriverNodeManager(IServerInternal server, ApplicationConfiguration configuration,
|
||||||
|
IDriver driver, ILogger<DriverNodeManager> logger)
|
||||||
|
: base(server, configuration, namespaceUris: $"urn:OtOpcUa:{driver.DriverInstanceId}")
|
||||||
|
{
|
||||||
|
_driver = driver;
|
||||||
|
_readable = driver as IReadable;
|
||||||
|
_writable = driver as IWritable;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override NodeStateCollection LoadPredefinedNodes(ISystemContext context) => new();
|
||||||
|
|
||||||
|
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
|
||||||
|
{
|
||||||
|
lock (Lock)
|
||||||
|
{
|
||||||
|
_driverRoot = new FolderState(null)
|
||||||
|
{
|
||||||
|
SymbolicName = _driver.DriverInstanceId,
|
||||||
|
ReferenceTypeId = ReferenceTypeIds.Organizes,
|
||||||
|
TypeDefinitionId = ObjectTypeIds.FolderType,
|
||||||
|
NodeId = new NodeId(_driver.DriverInstanceId, NamespaceIndex),
|
||||||
|
BrowseName = new QualifiedName(_driver.DriverInstanceId, NamespaceIndex),
|
||||||
|
DisplayName = new LocalizedText(_driver.DriverInstanceId),
|
||||||
|
EventNotifier = EventNotifiers.None,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Link under Objects folder so clients see the driver subtree at browse root.
|
||||||
|
if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out var references))
|
||||||
|
{
|
||||||
|
references = new List<IReference>();
|
||||||
|
externalReferences[ObjectIds.ObjectsFolder] = references;
|
||||||
|
}
|
||||||
|
references.Add(new NodeStateReference(ReferenceTypeIds.Organizes, false, _driverRoot.NodeId));
|
||||||
|
|
||||||
|
AddPredefinedNode(SystemContext, _driverRoot);
|
||||||
|
_currentFolder = _driverRoot;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------- IAddressSpaceBuilder implementation (PR 15 contract) -------
|
||||||
|
|
||||||
|
public IAddressSpaceBuilder Folder(string browseName, string displayName)
|
||||||
|
{
|
||||||
|
lock (Lock)
|
||||||
|
{
|
||||||
|
var folder = new FolderState(_currentFolder)
|
||||||
|
{
|
||||||
|
SymbolicName = browseName,
|
||||||
|
ReferenceTypeId = ReferenceTypeIds.Organizes,
|
||||||
|
TypeDefinitionId = ObjectTypeIds.FolderType,
|
||||||
|
NodeId = new NodeId($"{_currentFolder.NodeId.Identifier}/{browseName}", NamespaceIndex),
|
||||||
|
BrowseName = new QualifiedName(browseName, NamespaceIndex),
|
||||||
|
DisplayName = new LocalizedText(displayName),
|
||||||
|
};
|
||||||
|
_currentFolder.AddChild(folder);
|
||||||
|
AddPredefinedNode(SystemContext, folder);
|
||||||
|
return new NestedBuilder(this, folder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
|
||||||
|
{
|
||||||
|
lock (Lock)
|
||||||
|
{
|
||||||
|
var v = new BaseDataVariableState(_currentFolder)
|
||||||
|
{
|
||||||
|
SymbolicName = browseName,
|
||||||
|
ReferenceTypeId = ReferenceTypeIds.Organizes,
|
||||||
|
TypeDefinitionId = VariableTypeIds.BaseDataVariableType,
|
||||||
|
NodeId = new NodeId(attributeInfo.FullName, NamespaceIndex),
|
||||||
|
BrowseName = new QualifiedName(browseName, NamespaceIndex),
|
||||||
|
DisplayName = new LocalizedText(displayName),
|
||||||
|
DataType = MapDataType(attributeInfo.DriverDataType),
|
||||||
|
ValueRank = attributeInfo.IsArray ? ValueRanks.OneDimension : ValueRanks.Scalar,
|
||||||
|
AccessLevel = AccessLevels.CurrentReadOrWrite,
|
||||||
|
UserAccessLevel = AccessLevels.CurrentReadOrWrite,
|
||||||
|
Historizing = attributeInfo.IsHistorized,
|
||||||
|
};
|
||||||
|
_currentFolder.AddChild(v);
|
||||||
|
AddPredefinedNode(SystemContext, v);
|
||||||
|
_variablesByFullRef[attributeInfo.FullName] = v;
|
||||||
|
|
||||||
|
v.OnReadValue = OnReadValue;
|
||||||
|
v.OnWriteValue = OnWriteValue;
|
||||||
|
return new VariableHandle(this, v, attributeInfo.FullName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddProperty(string browseName, DriverDataType dataType, object? value)
|
||||||
|
{
|
||||||
|
lock (Lock)
|
||||||
|
{
|
||||||
|
var p = new PropertyState(_currentFolder)
|
||||||
|
{
|
||||||
|
SymbolicName = browseName,
|
||||||
|
ReferenceTypeId = ReferenceTypeIds.HasProperty,
|
||||||
|
TypeDefinitionId = VariableTypeIds.PropertyType,
|
||||||
|
NodeId = new NodeId($"{_currentFolder.NodeId.Identifier}/{browseName}", NamespaceIndex),
|
||||||
|
BrowseName = new QualifiedName(browseName, NamespaceIndex),
|
||||||
|
DisplayName = new LocalizedText(browseName),
|
||||||
|
DataType = MapDataType(dataType),
|
||||||
|
ValueRank = ValueRanks.Scalar,
|
||||||
|
Value = value,
|
||||||
|
};
|
||||||
|
_currentFolder.AddChild(p);
|
||||||
|
AddPredefinedNode(SystemContext, p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ServiceResult OnReadValue(ISystemContext context, NodeState node, NumericRange indexRange,
|
||||||
|
QualifiedName dataEncoding, ref object? value, ref StatusCode statusCode, ref DateTime timestamp)
|
||||||
|
{
|
||||||
|
if (_readable is null)
|
||||||
|
{
|
||||||
|
statusCode = StatusCodes.BadNotReadable;
|
||||||
|
return ServiceResult.Good;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var fullRef = node.NodeId.Identifier as string ?? "";
|
||||||
|
var result = _readable.ReadAsync([fullRef], CancellationToken.None).GetAwaiter().GetResult();
|
||||||
|
if (result.Count == 0)
|
||||||
|
{
|
||||||
|
statusCode = StatusCodes.BadNoData;
|
||||||
|
return ServiceResult.Good;
|
||||||
|
}
|
||||||
|
var snap = result[0];
|
||||||
|
value = snap.Value;
|
||||||
|
statusCode = snap.StatusCode;
|
||||||
|
timestamp = snap.ServerTimestampUtc;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "OnReadValue failed for {NodeId}", node.NodeId);
|
||||||
|
statusCode = StatusCodes.BadInternalError;
|
||||||
|
}
|
||||||
|
return ServiceResult.Good;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static NodeId MapDataType(DriverDataType t) => t switch
|
||||||
|
{
|
||||||
|
DriverDataType.Boolean => DataTypeIds.Boolean,
|
||||||
|
DriverDataType.Int32 => DataTypeIds.Int32,
|
||||||
|
DriverDataType.Float32 => DataTypeIds.Float,
|
||||||
|
DriverDataType.Float64 => DataTypeIds.Double,
|
||||||
|
DriverDataType.String => DataTypeIds.String,
|
||||||
|
DriverDataType.DateTime => DataTypeIds.DateTime,
|
||||||
|
_ => DataTypeIds.BaseDataType,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Nested builder returned by <see cref="Folder"/>. Temporarily retargets the parent's
|
||||||
|
/// <see cref="_currentFolder"/> during each call so Variable/Folder calls land under the
|
||||||
|
/// correct subtree. Not thread-safe if callers drive Discovery concurrently — but
|
||||||
|
/// <c>GenericDriverNodeManager</c> discovery is sequential per driver.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class NestedBuilder(DriverNodeManager owner, FolderState folder) : IAddressSpaceBuilder
|
||||||
|
{
|
||||||
|
public IAddressSpaceBuilder Folder(string browseName, string displayName)
|
||||||
|
{
|
||||||
|
var prior = owner._currentFolder;
|
||||||
|
owner._currentFolder = folder;
|
||||||
|
try { return owner.Folder(browseName, displayName); }
|
||||||
|
finally { owner._currentFolder = prior; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
|
||||||
|
{
|
||||||
|
var prior = owner._currentFolder;
|
||||||
|
owner._currentFolder = folder;
|
||||||
|
try { return owner.Variable(browseName, displayName, attributeInfo); }
|
||||||
|
finally { owner._currentFolder = prior; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddProperty(string browseName, DriverDataType dataType, object? value)
|
||||||
|
{
|
||||||
|
var prior = owner._currentFolder;
|
||||||
|
owner._currentFolder = folder;
|
||||||
|
try { owner.AddProperty(browseName, dataType, value); }
|
||||||
|
finally { owner._currentFolder = prior; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class VariableHandle : IVariableHandle
|
||||||
|
{
|
||||||
|
private readonly DriverNodeManager _owner;
|
||||||
|
private readonly BaseDataVariableState _variable;
|
||||||
|
public string FullReference { get; }
|
||||||
|
|
||||||
|
public VariableHandle(DriverNodeManager owner, BaseDataVariableState variable, string fullRef)
|
||||||
|
{
|
||||||
|
_owner = owner;
|
||||||
|
_variable = variable;
|
||||||
|
FullReference = fullRef;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo info)
|
||||||
|
{
|
||||||
|
lock (_owner.Lock)
|
||||||
|
{
|
||||||
|
var alarm = new AlarmConditionState(_variable)
|
||||||
|
{
|
||||||
|
SymbolicName = _variable.BrowseName.Name + "_Condition",
|
||||||
|
ReferenceTypeId = ReferenceTypeIds.HasComponent,
|
||||||
|
NodeId = new NodeId(FullReference + ".Condition", _owner.NamespaceIndex),
|
||||||
|
BrowseName = new QualifiedName(_variable.BrowseName.Name + "_Condition", _owner.NamespaceIndex),
|
||||||
|
DisplayName = new LocalizedText(info.SourceName),
|
||||||
|
};
|
||||||
|
alarm.Create(_owner.SystemContext, alarm.NodeId, alarm.BrowseName, alarm.DisplayName, false);
|
||||||
|
alarm.SourceName.Value = info.SourceName;
|
||||||
|
alarm.Severity.Value = (ushort)MapSeverity(info.InitialSeverity);
|
||||||
|
alarm.Message.Value = new LocalizedText(info.InitialDescription ?? info.SourceName);
|
||||||
|
alarm.EnabledState.Value = new LocalizedText("Enabled");
|
||||||
|
alarm.EnabledState.Id.Value = true;
|
||||||
|
alarm.Retain.Value = false;
|
||||||
|
alarm.AckedState.Value = new LocalizedText("Acknowledged");
|
||||||
|
alarm.AckedState.Id.Value = true;
|
||||||
|
alarm.ActiveState.Value = new LocalizedText("Inactive");
|
||||||
|
alarm.ActiveState.Id.Value = false;
|
||||||
|
|
||||||
|
_variable.AddChild(alarm);
|
||||||
|
_owner.AddPredefinedNode(_owner.SystemContext, alarm);
|
||||||
|
|
||||||
|
return new ConditionSink(_owner, alarm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int MapSeverity(AlarmSeverity s) => s switch
|
||||||
|
{
|
||||||
|
AlarmSeverity.Low => 250,
|
||||||
|
AlarmSeverity.Medium => 500,
|
||||||
|
AlarmSeverity.High => 700,
|
||||||
|
AlarmSeverity.Critical => 900,
|
||||||
|
_ => 500,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class ConditionSink(DriverNodeManager owner, AlarmConditionState alarm)
|
||||||
|
: IAlarmConditionSink
|
||||||
|
{
|
||||||
|
public void OnTransition(AlarmEventArgs args)
|
||||||
|
{
|
||||||
|
lock (owner.Lock)
|
||||||
|
{
|
||||||
|
alarm.Severity.Value = (ushort)MapSeverity(args.Severity);
|
||||||
|
alarm.Time.Value = args.SourceTimestampUtc;
|
||||||
|
alarm.Message.Value = new LocalizedText(args.Message);
|
||||||
|
|
||||||
|
// Map the driver's transition type to OPC UA Part 9 state. The driver uses
|
||||||
|
// AlarmEventArgs but the state transition kind is encoded in AlarmType by
|
||||||
|
// convention — Galaxy's GalaxyAlarmTracker emits "Active"/"Acknowledged"/"Inactive".
|
||||||
|
switch (args.AlarmType)
|
||||||
|
{
|
||||||
|
case "Active":
|
||||||
|
alarm.SetActiveState(owner.SystemContext, true);
|
||||||
|
alarm.SetAcknowledgedState(owner.SystemContext, false);
|
||||||
|
alarm.Retain.Value = true;
|
||||||
|
break;
|
||||||
|
case "Acknowledged":
|
||||||
|
alarm.SetAcknowledgedState(owner.SystemContext, true);
|
||||||
|
break;
|
||||||
|
case "Inactive":
|
||||||
|
alarm.SetActiveState(owner.SystemContext, false);
|
||||||
|
// Retain stays true until the condition is both Inactive and Acknowledged
|
||||||
|
// so alarm clients keep the record in their condition refresh snapshot.
|
||||||
|
if (alarm.AckedState.Id.Value) alarm.Retain.Value = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
alarm.ClearChangeMasks(owner.SystemContext, true);
|
||||||
|
alarm.ReportEvent(owner.SystemContext, alarm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int MapSeverity(AlarmSeverity s) => s switch
|
||||||
|
{
|
||||||
|
AlarmSeverity.Low => 250,
|
||||||
|
AlarmSeverity.Medium => 500,
|
||||||
|
AlarmSeverity.High => 700,
|
||||||
|
AlarmSeverity.Critical => 900,
|
||||||
|
_ => 500,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Per-variable write hook wired on each <see cref="BaseDataVariableState"/>. Routes the
|
||||||
|
/// value into the driver's <see cref="IWritable"/> and surfaces its per-tag status code.
|
||||||
|
/// </summary>
|
||||||
|
private ServiceResult OnWriteValue(ISystemContext context, NodeState node, NumericRange indexRange,
|
||||||
|
QualifiedName dataEncoding, ref object? value, ref StatusCode statusCode, ref DateTime timestamp)
|
||||||
|
{
|
||||||
|
if (_writable is null) return StatusCodes.BadNotWritable;
|
||||||
|
var fullRef = node.NodeId.Identifier as string;
|
||||||
|
if (string.IsNullOrEmpty(fullRef)) return StatusCodes.BadNodeIdUnknown;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var results = _writable.WriteAsync(
|
||||||
|
[new DriverWriteRequest(fullRef!, value)],
|
||||||
|
CancellationToken.None).GetAwaiter().GetResult();
|
||||||
|
if (results.Count > 0 && results[0].StatusCode != 0)
|
||||||
|
{
|
||||||
|
statusCode = results[0].StatusCode;
|
||||||
|
return ServiceResult.Good;
|
||||||
|
}
|
||||||
|
return ServiceResult.Good;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Write failed for {FullRef}", fullRef);
|
||||||
|
return new ServiceResult(StatusCodes.BadInternalError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Diagnostics hook for tests — number of variables registered in this node manager.
|
||||||
|
internal int VariableCount => _variablesByFullRef.Count;
|
||||||
|
internal bool TryGetVariable(string fullRef, out BaseDataVariableState? v)
|
||||||
|
=> _variablesByFullRef.TryGetValue(fullRef, out v!);
|
||||||
|
}
|
||||||
62
src/ZB.MOM.WW.OtOpcUa.Server/OpcUa/OtOpcUaServer.cs
Normal file
62
src/ZB.MOM.WW.OtOpcUa.Server/OpcUa/OtOpcUaServer.cs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Opc.Ua;
|
||||||
|
using Opc.Ua.Server;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.OpcUa;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Server.OpcUa;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <see cref="StandardServer"/> subclass that wires one <see cref="DriverNodeManager"/> per
|
||||||
|
/// registered driver from <see cref="DriverHost"/>. Anonymous endpoint on
|
||||||
|
/// <c>opc.tcp://0.0.0.0:4840</c>, no security — PR 16 minimum-viable scope; LDAP + security
|
||||||
|
/// profiles are deferred to their own PR on top of this.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class OtOpcUaServer : StandardServer
|
||||||
|
{
|
||||||
|
private readonly DriverHost _driverHost;
|
||||||
|
private readonly ILoggerFactory _loggerFactory;
|
||||||
|
private readonly List<DriverNodeManager> _driverNodeManagers = new();
|
||||||
|
|
||||||
|
public OtOpcUaServer(DriverHost driverHost, ILoggerFactory loggerFactory)
|
||||||
|
{
|
||||||
|
_driverHost = driverHost;
|
||||||
|
_loggerFactory = loggerFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Read-only snapshot of the driver node managers materialized at server start. Used by
|
||||||
|
/// the generic-driver-node-manager-driven discovery flow after the server starts — the
|
||||||
|
/// host walks each entry and invokes
|
||||||
|
/// <c>GenericDriverNodeManager.BuildAddressSpaceAsync(manager)</c> passing the manager
|
||||||
|
/// as its own <see cref="IAddressSpaceBuilder"/>.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<DriverNodeManager> DriverNodeManagers => _driverNodeManagers;
|
||||||
|
|
||||||
|
protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration)
|
||||||
|
{
|
||||||
|
foreach (var driverId in _driverHost.RegisteredDriverIds)
|
||||||
|
{
|
||||||
|
var driver = _driverHost.GetDriver(driverId);
|
||||||
|
if (driver is null) continue;
|
||||||
|
|
||||||
|
var logger = _loggerFactory.CreateLogger<DriverNodeManager>();
|
||||||
|
var manager = new DriverNodeManager(server, configuration, driver, logger);
|
||||||
|
_driverNodeManagers.Add(manager);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new MasterNodeManager(server, configuration, null, _driverNodeManagers.ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override ServerProperties LoadServerProperties() => new()
|
||||||
|
{
|
||||||
|
ManufacturerName = "OtOpcUa",
|
||||||
|
ProductName = "OtOpcUa.Server",
|
||||||
|
ProductUri = "urn:OtOpcUa:Server",
|
||||||
|
SoftwareVersion = "2.0.0",
|
||||||
|
BuildNumber = "0",
|
||||||
|
BuildDate = DateTime.UtcNow,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -21,6 +21,8 @@
|
|||||||
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0"/>
|
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0"/>
|
||||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0"/>
|
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0"/>
|
||||||
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0"/>
|
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0"/>
|
||||||
|
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Server" Version="1.5.374.126"/>
|
||||||
|
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Configuration" Version="1.5.374.126"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -30,6 +32,9 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-37gx-xxp4-5rgx"/>
|
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-37gx-xxp4-5rgx"/>
|
||||||
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-w3x6-4m5h-cxqf"/>
|
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-w3x6-4m5h-cxqf"/>
|
||||||
|
<!-- OPCFoundation.NetStandard.Opc.Ua.Core advisory — v1 already uses this package at the
|
||||||
|
same version, risk already accepted in the v1 stack. -->
|
||||||
|
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-h958-fxgg-g7w3"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
using Shouldly;
|
||||||
|
using Xunit;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.OpcUa;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Core.Tests;
|
||||||
|
|
||||||
|
[Trait("Category", "Unit")]
|
||||||
|
public sealed class GenericDriverNodeManagerTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// BuildAddressSpaceAsync walks the driver's discovery through the caller's builder. Every
|
||||||
|
/// variable marked with MarkAsAlarmCondition captures its sink in the node manager; later,
|
||||||
|
/// IAlarmSource.OnAlarmEvent payloads are routed by SourceNodeId to the matching sink.
|
||||||
|
/// This is the plumbing that PR 16's concrete OPC UA builder will use to update the actual
|
||||||
|
/// AlarmConditionState nodes.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task Alarm_events_are_routed_to_the_sink_registered_for_the_matching_source_node_id()
|
||||||
|
{
|
||||||
|
var driver = new FakeDriver();
|
||||||
|
var builder = new RecordingBuilder();
|
||||||
|
using var nm = new GenericDriverNodeManager(driver);
|
||||||
|
|
||||||
|
await nm.BuildAddressSpaceAsync(builder, CancellationToken.None);
|
||||||
|
|
||||||
|
builder.Alarms.Count.ShouldBe(2);
|
||||||
|
nm.TrackedAlarmSources.Count.ShouldBe(2);
|
||||||
|
|
||||||
|
// Simulate the driver raising a transition for one of the alarms.
|
||||||
|
var args = new AlarmEventArgs(
|
||||||
|
SubscriptionHandle: new FakeHandle("s1"),
|
||||||
|
SourceNodeId: "Tank.HiHi",
|
||||||
|
ConditionId: "cond-1",
|
||||||
|
AlarmType: "Tank.HiHi",
|
||||||
|
Message: "Level exceeded",
|
||||||
|
Severity: AlarmSeverity.High,
|
||||||
|
SourceTimestampUtc: DateTime.UtcNow);
|
||||||
|
driver.RaiseAlarm(args);
|
||||||
|
|
||||||
|
builder.Alarms["Tank.HiHi"].Received.Count.ShouldBe(1);
|
||||||
|
builder.Alarms["Tank.HiHi"].Received[0].Message.ShouldBe("Level exceeded");
|
||||||
|
// The other alarm sink never received a payload — fan-out is tag-scoped.
|
||||||
|
builder.Alarms["Heater.OverTemp"].Received.Count.ShouldBe(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Non_alarm_variables_do_not_register_sinks()
|
||||||
|
{
|
||||||
|
var driver = new FakeDriver();
|
||||||
|
var builder = new RecordingBuilder();
|
||||||
|
using var nm = new GenericDriverNodeManager(driver);
|
||||||
|
|
||||||
|
await nm.BuildAddressSpaceAsync(builder, CancellationToken.None);
|
||||||
|
|
||||||
|
// FakeDriver registers 2 alarm-bearing variables + 1 plain variable.
|
||||||
|
nm.TrackedAlarmSources.ShouldNotContain("Tank.Level"); // the plain one
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unknown_source_node_id_is_dropped_silently()
|
||||||
|
{
|
||||||
|
var driver = new FakeDriver();
|
||||||
|
var builder = new RecordingBuilder();
|
||||||
|
using var nm = new GenericDriverNodeManager(driver);
|
||||||
|
await nm.BuildAddressSpaceAsync(builder, CancellationToken.None);
|
||||||
|
|
||||||
|
driver.RaiseAlarm(new AlarmEventArgs(
|
||||||
|
new FakeHandle("s1"), "Unknown.Source", "c", "t", "m", AlarmSeverity.Low, DateTime.UtcNow));
|
||||||
|
|
||||||
|
builder.Alarms.Values.All(s => s.Received.Count == 0).ShouldBeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Dispose_unsubscribes_from_OnAlarmEvent()
|
||||||
|
{
|
||||||
|
var driver = new FakeDriver();
|
||||||
|
var builder = new RecordingBuilder();
|
||||||
|
var nm = new GenericDriverNodeManager(driver);
|
||||||
|
await nm.BuildAddressSpaceAsync(builder, CancellationToken.None);
|
||||||
|
|
||||||
|
nm.Dispose();
|
||||||
|
|
||||||
|
driver.RaiseAlarm(new AlarmEventArgs(
|
||||||
|
new FakeHandle("s1"), "Tank.HiHi", "c", "t", "m", AlarmSeverity.Low, DateTime.UtcNow));
|
||||||
|
|
||||||
|
// No sink should have received it — the forwarder was detached.
|
||||||
|
builder.Alarms["Tank.HiHi"].Received.Count.ShouldBe(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- test doubles ---
|
||||||
|
|
||||||
|
private sealed class FakeDriver : IDriver, ITagDiscovery, IAlarmSource
|
||||||
|
{
|
||||||
|
public string DriverInstanceId => "fake";
|
||||||
|
public string DriverType => "Fake";
|
||||||
|
public event EventHandler<AlarmEventArgs>? OnAlarmEvent;
|
||||||
|
|
||||||
|
public Task InitializeAsync(string driverConfigJson, CancellationToken ct) => Task.CompletedTask;
|
||||||
|
public Task ReinitializeAsync(string driverConfigJson, CancellationToken ct) => Task.CompletedTask;
|
||||||
|
public Task ShutdownAsync(CancellationToken ct) => Task.CompletedTask;
|
||||||
|
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
|
||||||
|
public long GetMemoryFootprint() => 0;
|
||||||
|
public Task FlushOptionalCachesAsync(CancellationToken ct) => Task.CompletedTask;
|
||||||
|
|
||||||
|
public Task DiscoverAsync(IAddressSpaceBuilder builder, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var folder = builder.Folder("Tank", "Tank");
|
||||||
|
var lvl = folder.Variable("Level", "Level", new DriverAttributeInfo(
|
||||||
|
"Tank.Level", DriverDataType.Float64, false, null, SecurityClassification.FreeAccess, false, IsAlarm: false));
|
||||||
|
var hiHi = folder.Variable("HiHi", "HiHi", new DriverAttributeInfo(
|
||||||
|
"Tank.HiHi", DriverDataType.Boolean, false, null, SecurityClassification.FreeAccess, false, IsAlarm: true));
|
||||||
|
hiHi.MarkAsAlarmCondition(new AlarmConditionInfo("Tank.HiHi", AlarmSeverity.High, "High-high alarm"));
|
||||||
|
|
||||||
|
var heater = builder.Folder("Heater", "Heater");
|
||||||
|
var ot = heater.Variable("OverTemp", "OverTemp", new DriverAttributeInfo(
|
||||||
|
"Heater.OverTemp", DriverDataType.Boolean, false, null, SecurityClassification.FreeAccess, false, IsAlarm: true));
|
||||||
|
ot.MarkAsAlarmCondition(new AlarmConditionInfo("Heater.OverTemp", AlarmSeverity.Critical, "Over-temperature"));
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RaiseAlarm(AlarmEventArgs args) => OnAlarmEvent?.Invoke(this, args);
|
||||||
|
|
||||||
|
public Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(IReadOnlyList<string> _, CancellationToken __)
|
||||||
|
=> Task.FromResult<IAlarmSubscriptionHandle>(new FakeHandle("sub"));
|
||||||
|
public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle _, CancellationToken __) => Task.CompletedTask;
|
||||||
|
public Task AcknowledgeAsync(IReadOnlyList<AlarmAcknowledgeRequest> _, CancellationToken __) => Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class FakeHandle(string diagnosticId) : IAlarmSubscriptionHandle
|
||||||
|
{
|
||||||
|
public string DiagnosticId { get; } = diagnosticId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RecordingBuilder : IAddressSpaceBuilder
|
||||||
|
{
|
||||||
|
public Dictionary<string, RecordingSink> Alarms { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
public IAddressSpaceBuilder Folder(string _, string __) => this;
|
||||||
|
|
||||||
|
public IVariableHandle Variable(string _, string __, DriverAttributeInfo info)
|
||||||
|
=> new Handle(info.FullName, Alarms);
|
||||||
|
|
||||||
|
public void AddProperty(string _, DriverDataType __, object? ___) { }
|
||||||
|
|
||||||
|
public sealed class Handle(string fullRef, Dictionary<string, RecordingSink> alarms) : IVariableHandle
|
||||||
|
{
|
||||||
|
public string FullReference { get; } = fullRef;
|
||||||
|
public IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo _)
|
||||||
|
{
|
||||||
|
var sink = new RecordingSink();
|
||||||
|
alarms[FullReference] = sink;
|
||||||
|
return sink;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class RecordingSink : IAlarmConditionSink
|
||||||
|
{
|
||||||
|
public List<AlarmEventArgs> Received { get; } = new();
|
||||||
|
public void OnTransition(AlarmEventArgs args) => Received.Add(args);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ public sealed class RecordingAddressSpaceBuilder : IAddressSpaceBuilder
|
|||||||
public List<RecordedFolder> Folders { get; } = new();
|
public List<RecordedFolder> Folders { get; } = new();
|
||||||
public List<RecordedVariable> Variables { get; } = new();
|
public List<RecordedVariable> Variables { get; } = new();
|
||||||
public List<RecordedProperty> Properties { get; } = new();
|
public List<RecordedProperty> Properties { get; } = new();
|
||||||
|
public List<RecordedAlarmCondition> AlarmConditions { get; } = new();
|
||||||
|
|
||||||
public IAddressSpaceBuilder Folder(string browseName, string displayName)
|
public IAddressSpaceBuilder Folder(string browseName, string displayName)
|
||||||
{
|
{
|
||||||
@@ -22,7 +23,7 @@ public sealed class RecordingAddressSpaceBuilder : IAddressSpaceBuilder
|
|||||||
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
|
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
|
||||||
{
|
{
|
||||||
Variables.Add(new RecordedVariable(browseName, displayName, attributeInfo));
|
Variables.Add(new RecordedVariable(browseName, displayName, attributeInfo));
|
||||||
return new RecordedVariableHandle(attributeInfo.FullName);
|
return new RecordedVariableHandle(attributeInfo.FullName, AlarmConditions);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void AddProperty(string browseName, DriverDataType dataType, object? value)
|
public void AddProperty(string browseName, DriverDataType dataType, object? value)
|
||||||
@@ -33,6 +34,37 @@ public sealed class RecordingAddressSpaceBuilder : IAddressSpaceBuilder
|
|||||||
public sealed record RecordedFolder(string BrowseName, string DisplayName);
|
public sealed record RecordedFolder(string BrowseName, string DisplayName);
|
||||||
public sealed record RecordedVariable(string BrowseName, string DisplayName, DriverAttributeInfo AttributeInfo);
|
public sealed record RecordedVariable(string BrowseName, string DisplayName, DriverAttributeInfo AttributeInfo);
|
||||||
public sealed record RecordedProperty(string BrowseName, DriverDataType DataType, object? Value);
|
public sealed record RecordedProperty(string BrowseName, DriverDataType DataType, object? Value);
|
||||||
|
public sealed record RecordedAlarmCondition(string SourceNodeId, AlarmConditionInfo Info);
|
||||||
|
public sealed record RecordedAlarmTransition(string SourceNodeId, AlarmEventArgs Args);
|
||||||
|
|
||||||
private sealed record RecordedVariableHandle(string FullReference) : IVariableHandle;
|
/// <summary>
|
||||||
|
/// Sink the tests assert on to verify the alarm event forwarder routed a transition
|
||||||
|
/// to the correct source-node-id. One entry per <see cref="IAlarmSource.OnAlarmEvent"/>.
|
||||||
|
/// </summary>
|
||||||
|
public List<RecordedAlarmTransition> AlarmTransitions { get; } = new();
|
||||||
|
|
||||||
|
private sealed class RecordedVariableHandle : IVariableHandle
|
||||||
|
{
|
||||||
|
private readonly List<RecordedAlarmCondition> _conditions;
|
||||||
|
public string FullReference { get; }
|
||||||
|
public RecordedVariableHandle(string fullReference, List<RecordedAlarmCondition> conditions)
|
||||||
|
{
|
||||||
|
FullReference = fullReference;
|
||||||
|
_conditions = conditions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo info)
|
||||||
|
{
|
||||||
|
_conditions.Add(new RecordedAlarmCondition(FullReference, info));
|
||||||
|
return new RecordingSink(FullReference);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RecordingSink : IAlarmConditionSink
|
||||||
|
{
|
||||||
|
public string SourceNodeId { get; }
|
||||||
|
public List<AlarmEventArgs> Received { get; } = new();
|
||||||
|
public RecordingSink(string sourceNodeId) => SourceNodeId = sourceNodeId;
|
||||||
|
public void OnTransition(AlarmEventArgs args) => Received.Add(args);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-37gx-xxp4-5rgx"/>
|
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-37gx-xxp4-5rgx"/>
|
||||||
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-w3x6-4m5h-cxqf"/>
|
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-w3x6-4m5h-cxqf"/>
|
||||||
|
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-h958-fxgg-g7w3"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
Reference in New Issue
Block a user