Files
UA-.NETStandard/tests/Opc.Ua.AMB.Tests/AmbClientServerE2eTests.cs
Klaus LandsdorfandMarc Schier b25c1f6ad4 Asset Management Basics: the OPC 10000-110 companion SDK (#4662)
# Description

Stacked on #4650. Until that is merged, this PR also shows its commits;
the six commits of this PR start after `fix(server): keep conformance
unit aggregation idempotent and ordered with registrations`.

This adds OPC 10000-110 Asset Management Basics 1.01.1
(`http://opcfoundation.org/UA/AMB/`) as a companion SDK, in the pattern
of the DI, Machinery, Pumps and Scales packages. The tracking issue
#4649 describes the scope, the design and the open questions. In short:

| Package | Content |
|---|---|
| `Opc.Ua.AMB` | the model generated by the source generator from the
unmodified NodeSet, plus the contracts server and client share
(`AssetFaultSeverity`, `AssetLocationKind`, `MaintenanceStateKind`,
`DocumentationLinkProperties`) |
| `Opc.Ua.AMB.Server` | a sidecar node manager next to the owner of the
Device Integration address space (`AddOpcUaDi`, `AddMachinery`,
`AddPumps` or `AddScales`), the asset registry `IAssetManagement` with a
fluent builder, `AddAssetManagement()` hosting, memory and file system
stores, the AMB conformance units and server facet |
| `Opc.Ua.AMB.Client` | `AmbClient`: discovery, identification, health
alarm and maintenance streams, documentation links, locations, structure
and snapshots, plus `AddAssetManagementClient()` |

**Sidecar.** An asset stays in the node manager that owns it. Everything
AMB adds to it (`DeviceHealth`, health alarms, maintenance conditions,
the DocumentationLinks AddIn, AssetId and the other properties) is
created there. The AMB node manager serves the AMB model, the alias
categories `Assets`, `AssetsByProductInstanceUri` and `AssetsByAssetId`
below `0:Aliases`, the location hierarchies below `0:Locations` and the
server-specific alarm and condition types. Owners register assets with
the shared registry from their setup, in either startup order.

**Implemented conformance units** (Table 54): Asset Identification,
Configurable Asset Identification, Discovery by ProductInstanceUri and
by AssetId, Health Status Base, Alarms, Root Causes and Alarm
Categories, Version Information, Operation Counters (inspected only; AMB
defines no counters), DocumentationLinks Base, Edit Base and Edit
Advanced, Requirements, Capabilities, Classification, Current and Future
Maintenance Activities, Local Time, the three location properties and
both location object hierarchies, Sub-assets and Asset relations. The
two history units (Health Tracking, Past Maintenance Activities) are not
part of this PR. `docs/AMB.md` has the matrix with the rule the server
applies for each unit and whether a test checks it over a session.

**Dependency on #4650.** The health alarms and maintenance conditions
are created through `CreateAlarm<TState>`, and the conformance units
follow the registered assets through the recomputation in
`ConformanceUnitsManager`.

## Changes

Six commits, each building on its own:

1. **`feat(amb)`: model package** (`src/Opc.Ua.AMB/`, about 2.4k lines,
of which the NodeSet and the two identifier tables are 1.6k).
- The NodeSet is the publication from `UA-Nodeset/latest/AMB`, byte for
byte (git blob `21f9475b646e9c5508171277ffe5b74edbeb0a58`).
`.gitattributes` checks it out with LF endings, because a test pins its
SHA-256.
- The published identifier table is vendored unchanged; a derived table
pins the symbol-to-NodeId mapping, and the generator fails the build
when they disagree. `tools/nodesets/README.md` documents the one new
kind of renamed symbol (top-level instances below `0:Aliases` and
`0:Locations`).
2. **`feat(amb)`: server package** (`src/Opc.Ua.AMB.Server/`, about
10.7k lines). Node manager, registry and builders, discovery, health,
maintenance (`MaintenanceEventStateMachine` with all transitions),
documentation links, locations, version information, classification
(IRDI dictionary entries below `Server/Dictionaries`) and structure,
stores, conformance evaluation, hosting. Log messages use the EventId
block 8300 to 8379, after Pumps (8100) and Scales (8200).
3. **`feat(amb)`: client package** (`src/Opc.Ua.AMB.Client/`, about 3.0k
lines). Calls AddLink and RemoveLink through the generated
`DocumentationLinksTypeClient`.
4. **`test(amb)`: test suite** (`tests/Opc.Ua.AMB.Tests/`, 163 tests,
about 8.8k lines; commit 6 adds one more).
5. **`docs(amb)`: guide and samples**: `docs/AMB.md`, links from
`README.md`, `docs/README.md`, `docs/Samples.md` and
`docs/AliasNames.md`; `samples/AMB/AmbServer` (AMB next to
`AddMachinery`: two DI devices and a Machinery press as assets, with a
simulation) and `samples/AMB/AmbClient`. The sample server listens on
62553, which no other sample uses.

6. **`feat(amb)`: tell the links users added from the links of the
manufacturer.** OPC 10000-110 gives a client no way to see which links
`RemoveLink` accepts (§10.5.4: only those `AddLink` created). As §10.5.1
lets vendors add metadata Properties to the links, the server gives
every link `AddLink` created, and every such link restored after a
restart, the `Boolean` Property `UserLink` (`true`), qualified with its
namespace of server-specific types, with a NodeId derived from the
persisted link identifier; declared links carry none, and `RemoveLink`
deletes it with the link. `DocumentationLinkRecord` gets the additive
`IsUserLink`, which `ReadDocumentationLinksAsync` fills with one Browse
over all links and one Read of the markers found (comparing the name
only, as the namespace is configurable; `false` for a server that does
not mark links). The name is shared as
`DocumentationLinkProperties.UserLink`.

`UA.slnx` and `.azurepipelines/expected-packages.txt` get the new
projects and packages in the commit that adds them.

All projects target `net48;net8.0;net9.0;net10.0` through the repository
properties (`LibTargetFrameworks`, `TestsTargetFrameworks`,
`AppTargetFrameworks`); `IsAotCompatible` and `PublishAot` are set from
net10.0 on, as in the other companion projects.

## Tests

- **`Opc.Ua.AMB.Tests`: 164 tests**, most of them against a hosted
server over real client sessions:
- the model: the SHA-256 of the NodeSet and the generator behaviours AMB
is the first companion model to rely on;
- each building block in-process and over a session: discovery through
every category with NodeVersion and model change events, AssetId writes,
health alarms and maintenance activities through all transitions with
acknowledgement, AddLink and RemoveLink, locations and structure, the
advertised conformance units and the facet;
  - a restart with the file system stores (links and AssetId survive);
- the `UserLink` marker: present on an added link only, the same NodeId
after a restart, removed with `RemoveLink`, and `IsUserLink` on the
client in the snapshot, after `AddLink`, after a restart and after
`RemoveLink`;
- composition with `AddOpcUaDi` (both startup orders), `AddPumps` and
`AddMachinery`;
- `AmbClient` end to end against a hosted server, including a Machinery
machine as an asset.
- **Results (macOS, local):** 164 passed / 0 failed on net10.0 and on
net8.0. .NET Framework is covered by the fork CI's Windows legs.
- **Coverage** of the three AMB assemblies (coverlet with
`tests/coverlet.runsettings.xml`, net10.0, generated `*.g.cs`,
`*TypeClient` proxies and `*Log` classes excluded): lines 93.9 % (4890
of 5206), branches 84.0 % (1294 of 1539); model 100 %, client 94.5 %,
server 93.4 %.
- **Build:** the three packages, the tests and the two samples build
without warnings for net48, net8.0, net9.0 and net10.0; `UA.slnx` builds
in Release (its warnings are all in files this PR does not touch, as on
master). `dotnet format` (whitespace, style, analyzers with `--severity
info`) reports nothing on the 95 changed C# files.
- **Samples:** `AmbServer` and `AmbClient` ran against each other on
net10.0: the client discovered the three assets, printed their snapshots
and the location hierarchies, added and removed a documentation link and
streamed alarms and maintenance.
- Fork CI (full matrix incl. macOS) and CodeQL: green on the same five
package commits before the rebase onto the current #4650 head — [CI run
37144486107](https://github.com/biancode/UA-.NETStandard/actions/runs/37144486107),
[CodeQL run
37144487873](https://github.com/biancode/UA-.NETStandard/actions/runs/37144487873).
The run on the current head (rebased, plus the user-link commit; AMB
tests 164/164 locally on net10.0) is in progress: [CI run
37203517457](https://github.com/biancode/UA-.NETStandard/actions/runs/37203517457).

## Notes for review

- **Size.** About 26.8k lines, larger than each of the companion PRs
#4577 to #4580. Without changes to the code it splits into the model,
server and server tests, and the client, end-to-end tests, samples and
docs on top; the issue asks which you prefer.
- **Interfaces on types.** §9.4.1 and §12.1 ask for alarm and condition
types that implement `IRootCauseIndicationType` and
`IMaintenanceEventType`. The server creates subtypes of the DI alarm
types in its own type namespace (`urn:opcua-netstandard:amb:types`);
`UseServerDefinedAlarmTypes = false` uses `HasInterface` on the instance
instead, and then does not report the units that need the type-level
interfaces.
- **Conformance unit names** follow Tables 54 to 56; the profile
database has no AMB entries yet. The QualifiedNames are in namespace 0,
as DI and Machinery publish theirs (question 5 in the issue).
- **Generator gap.** Children a NodeSet gives to a top-level instance
(here the `NodeVersion` properties of the alias categories) get no
identifier constants. The fix changes the identifiers of other generated
models, the reference server's among them, so it is not part of this PR;
`AmbModelTests.NodeVersionHasNoIdentifierConstant` records it and fails
once the generator emits the constants.
- **net48.** The code that the SDK so far only built for .NET 8 and
later uses the `NET5_0_OR_GREATER` pattern of `JsonEncoder` for
`Enum.IsDefined` and API forms that .NET Framework has (`string.Format`,
`Guid.ToString(format, provider)`); the tests use a small async file
helper instead of `File.WriteAllTextAsync`.
- **User links.** The `UserLink` Property is metadata of this server,
not an AMB name: commit 6 explains why and how a client uses it. Changed
lines of that commit covered: 69/70 (the one line left is the loop
continuation for a link that has other Properties but no marker).
- **Known limitations** are listed in the guide: the `DeviceHealth`
SourceTimestamp across a restart, removing optional maintenance members
once set, `PatchIdentifiers`, locations only at the deepest level, and
the history units.

## Related Issues

- Part of #4649
- Stacked on #4650

## Checklist

- [x] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [x] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed. (The AMB
suite on net10.0 and net8.0 locally on macOS; .NET Framework is covered
by the fork CI's Windows net48 legs.)
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

---------

Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
2026-10-05 07:45:46 +02:00

745 lines
39 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Opc.Ua.AMB.Client;
using Opc.Ua.AMB.Server.Assets;
using Opc.Ua.AMB.Server.Health;
using Opc.Ua.AMB.Server.Maintenance;
using Opc.Ua.Client;
using Opc.Ua.Client.TestFramework;
using Opc.Ua.Di;
using Opc.Ua.Di.Server;
using Opc.Ua.Di.Server.Builders;
using Opc.Ua.Machinery.Server;
using Opc.Ua.Machinery.Server.Builders;
using Opc.Ua.Tests;
namespace Opc.Ua.AMB.Tests
{
/// <summary>
/// Drives a hosted Asset Management Basics server with the AMB client
/// over real sessions: discovery, identification, the AssetId move,
/// health alarms, maintenance, documentation links, locations and
/// structure, a restart with persistence, and a Machinery machine as an
/// asset.
/// </summary>
[TestFixture]
[Category("AMB")]
[Category("Hosting")]
[NonParallelizable]
public sealed class AmbClientServerE2eTests
{
private const string PumpUri = "urn:acme:pump:1";
private const string MotorUri = "urn:acme:motor:1";
private const string SensorUri = "urn:acme:sensor:7";
private static readonly ExpandedNodeId s_eclass = new("0173-1#01-ADN228#012", "urn:example:eclass");
private static readonly DateTimeUtc s_planned = new(new DateTime(2027, 3, 1, 8, 0, 0, DateTimeKind.Utc));
private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30);
private static readonly string[] s_levels = ["Plant1", "Plant1/Hall3", "Plant1/Hall3/Line2"];
[Test]
public async Task TheClientDiscoversAndReadsThePlantAsync()
{
await using Plant plant = await Plant.StartAsync(nameof(TheClientDiscoversAndReadsThePlantAsync), null)
.ConfigureAwait(false);
await using Connection connection = await Connection.OpenAsync(plant.Server, "discovery")
.ConfigureAwait(false);
AmbClient amb = connection.Client;
ArrayOf<NodeId> assets = await amb.DiscoverAssetsAsync().ConfigureAwait(false);
ArrayOf<AssetAlias> byUri = await amb
.FindAssetsAsync("urn:acme:pump:%", AssetAliasCategory.ByProductInstanceUri)
.ConfigureAwait(false);
ArrayOf<AssetAlias> byAssetId = await amb.FindAssetsAsync("P-1", AssetAliasCategory.ByAssetId)
.ConfigureAwait(false);
var browsed = new List<AssetAlias>();
await foreach (AssetAlias alias in amb
.EnumerateAssetsAsync(AssetAliasCategory.Assets)
.ConfigureAwait(false))
{
browsed.Add(alias);
}
NodeId pump = plant.Pump!.NodeId;
AssetSnapshot snapshot = await amb.ReadAssetAsync(pump).ConfigureAwait(false);
ArrayOf<AssetLocationNode> hierarchy = await amb.BrowseLocationsAsync(AssetLocationKind.Hierarchical)
.ConfigureAwait(false);
ArrayOf<AssetEntryRecord> requirements = await amb
.ReadEntriesAsync(pump, AssetEntryFolder.Requirements)
.ConfigureAwait(false);
var subAssets = new List<ExpandedNodeId>();
await foreach (ExpandedNodeId sub in amb.EnumerateSubAssetsAsync(pump).ConfigureAwait(false))
{
subAssets.Add(sub);
}
ArrayOf<AssetRelation> pumpRelations = await amb.ReadRelationsAsync(pump).ConfigureAwait(false);
ArrayOf<AssetRelation> sensorRelations = await amb.ReadRelationsAsync(plant.Sensor!.NodeId)
.ConfigureAwait(false);
DataValue profiles = await ReadAsync(
connection.Session,
Ua.VariableIds.Server_ServerCapabilities_ServerProfileArray).ConfigureAwait(false);
DataValue units = await ReadAsync(
connection.Session,
Ua.VariableIds.Server_ServerCapabilities_ConformanceUnits).ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(amb.IsSupported, Is.True);
Assert.That(
assets.ToArray(),
Is.EquivalentTo(new[] { plant.Motor!.NodeId, pump, plant.Sensor.NodeId }));
Assert.That(byUri.Count, Is.EqualTo(1));
Assert.That(byUri[0].Name, Is.EqualTo(PumpUri));
Assert.That(byAssetId.Count, Is.EqualTo(1));
Assert.That(
browsed.Count(alias => alias.Category == AssetAliasCategory.ByProductInstanceUri),
Is.EqualTo(3));
Assert.That(
browsed.Count(alias => alias.Category == AssetAliasCategory.ByAssetId),
Is.EqualTo(1),
"§8.2.3: the motor and the sensor have no AssetId and are not listed by it");
Assert.That(snapshot.Identification.ProductInstanceUri, Is.EqualTo(PumpUri));
Assert.That(snapshot.Identification.AssetId, Is.EqualTo("P-1"));
Assert.That(snapshot.Identification.HardwareRevision, Is.EqualTo("HW-1"));
Assert.That(snapshot.Identification.SoftwareRevision, Is.EqualTo("SW-1"));
Assert.That(snapshot.Identification.RevisionCounter, Is.EqualTo(1));
Assert.That(snapshot.DeviceHealth, Is.EqualTo(DeviceHealthEnumeration.NORMAL));
Assert.That(snapshot.HealthAlarms.Count, Is.EqualTo(1));
Assert.That(snapshot.HealthAlarms[0].ConditionName, Is.EqualTo("Fieldbus"));
Assert.That(snapshot.HealthAlarms[0].ConditionClass, Is.SameAs(AmbConditionClass.ConnectionFailure));
Assert.That(snapshot.HealthAlarms[0].IsActive, Is.False);
Assert.That(snapshot.HealthAlarms[0].PotentialRootCauses.Count, Is.EqualTo(1));
Assert.That(snapshot.MaintenanceActivities.Count, Is.EqualTo(1));
Assert.That(snapshot.MaintenanceActivities[0].State, Is.EqualTo(MaintenanceStateKind.Planned));
Assert.That(snapshot.MaintenanceActivities[0].PlannedDate, Is.EqualTo(s_planned));
Assert.That(snapshot.MaintenanceActivities[0].ConditionClass, Is.SameAs(AmbConditionClass.Inspection));
Assert.That(snapshot.DocumentationLinks.Count, Is.EqualTo(2));
Assert.That(
ListOf(snapshot.DocumentationLinks).Single(link => link.BrowseName.Name == "Manual").IsWritable,
Is.False);
Assert.That(
ListOf(snapshot.DocumentationLinks).Single(link => link.BrowseName.Name == "Handbook").IsWritable,
Is.True);
Assert.That(
ListOf(snapshot.DocumentationLinks).Select(link => link.IsUserLink),
Has.All.False,
"the manufacturer declared both links, so RemoveLink accepts neither");
Assert.That(snapshot.Context.HierarchicalLocation, Is.EqualTo("Plant1/Hall3/Line2"));
Assert.That(snapshot.Context.LocalTime?.Offset, Is.EqualTo((short)60));
Assert.That(snapshot.Context.Classifications.ToArray(), Does.Contain(s_eclass));
Assert.That(snapshot.Locations.Count, Is.EqualTo(1));
Assert.That(
ListOf(hierarchy).Select(location => location.Path),
Is.EqualTo(s_levels));
Assert.That(hierarchy[2].Assets.ToArray(), Does.Contain((ExpandedNodeId)pump));
Assert.That(snapshot.Locations[0].Location, Is.EqualTo(hierarchy[2].NodeId));
Assert.That(requirements.Count, Is.EqualTo(1));
Assert.That(requirements[0].Value.TryGetValue(out double voltage) ? voltage : 0, Is.EqualTo(24.0));
Assert.That(subAssets, Is.EqualTo(new[] { (ExpandedNodeId)plant.Motor.NodeId }));
Assert.That(
ListOf(sensorRelations).Select(relation => relation.ReferenceTypeId),
Does.Contain(Ua.ReferenceTypeIds.Utilizes));
Assert.That(
ListOf(pumpRelations).Any(relation =>
relation.IsInverse && relation.Target == (ExpandedNodeId)plant.Sensor.NodeId),
Is.True,
"the pump sees the inverse Utilizes of the sensor");
Assert.That(
profiles.WrappedValue.TryGetValue(out ArrayOf<string> profileUris) ? profileUris.ToArray() : [],
Does.Contain("http://opcfoundation.org/UA-Profile/AMB/Server/BaseServer"));
Assert.That(
units.WrappedValue.TryGetValue(out ArrayOf<QualifiedName> unitNames) ? unitNames.ToArray() : [],
Is.SupersetOf(new[]
{
new QualifiedName("AMB Asset Identification"),
new QualifiedName("AMB Asset Discovery by AssetId"),
new QualifiedName("AMB Hierarchical Location Objects"),
new QualifiedName("AMB Sub-assets"),
new QualifiedName("AMB Asset relations")
}));
});
}
[Test]
public async Task WritingTheAssetIdMovesTheAssetAsync()
{
await using Plant plant = await Plant.StartAsync(nameof(WritingTheAssetIdMovesTheAssetAsync), null)
.ConfigureAwait(false);
await using Connection connection = await Connection.OpenAsync(plant.Server, "assetid")
.ConfigureAwait(false);
AmbClient amb = connection.Client;
NodeId pump = plant.Pump!.NodeId;
string? before = await amb.ReadNodeVersionAsync(AssetAliasCategory.ByAssetId).ConfigureAwait(false);
int writes = 0;
string written = string.Empty;
using var cts = new CancellationTokenSource(s_timeout);
await using IAsyncEnumerator<AssetSetChange> changes = amb
.ObserveAssetSetChangesAsync(cancellationToken: cts.Token)
.GetAsyncEnumerator(cts.Token);
AssetSetChange change = await NextAsync(
changes,
async () =>
{
written = "P-" + (++writes + 1);
await amb.WriteAssetIdAsync(pump, written, cts.Token).ConfigureAwait(false);
},
candidate => candidate.Category == AssetAliasCategory.ByAssetId,
cts.Token).ConfigureAwait(false);
string? after = await amb.ReadNodeVersionAsync(AssetAliasCategory.ByAssetId).ConfigureAwait(false);
ArrayOf<AssetAlias> moved = await amb.FindAssetsAsync(written, AssetAliasCategory.ByAssetId)
.ConfigureAwait(false);
ArrayOf<AssetAlias> old = await amb.FindAssetsAsync("P-1", AssetAliasCategory.ByAssetId)
.ConfigureAwait(false);
AssetIdentificationRecord identification = await amb.ReadIdentificationAsync(pump).ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(change.Category, Is.EqualTo(AssetAliasCategory.ByAssetId));
Assert.That(after, Is.Not.EqualTo(before));
Assert.That(moved.Count, Is.EqualTo(1));
Assert.That(old.Count, Is.Zero);
Assert.That(identification.AssetId, Is.EqualTo(written));
});
ServiceResultException tooLong = Assert.ThrowsAsync<ServiceResultException>(
async () => await amb.WriteAssetIdAsync(pump, new string('x', 300)).ConfigureAwait(false))!;
ServiceResultException none = Assert.ThrowsAsync<ServiceResultException>(
async () => await amb.WriteAssetIdAsync(plant.Motor!.NodeId, "M-1").ConfigureAwait(false))!;
Assert.Multiple(() =>
{
Assert.That(tooLong.StatusCode, Is.EqualTo(StatusCodes.BadOutOfRange));
Assert.That(none.StatusCode, Is.EqualTo(StatusCodes.BadNodeIdUnknown), "the motor has no AssetId");
});
}
[Test]
public async Task TheClientFollowsAndAcknowledgesAHealthAlarmAsync()
{
await using Plant plant = await Plant
.StartAsync(nameof(TheClientFollowsAndAcknowledgesAHealthAlarmAsync), null)
.ConfigureAwait(false);
await using Connection connection = await Connection.OpenAsync(plant.Server, "alarms")
.ConfigureAwait(false);
AmbClient amb = connection.Client;
IAssetHealthAlarm fieldbus = plant.Pump!.Health!.Alarms[0];
var cable = new NodeId("Cable", plant.Server.Manager.InstanceNamespaceIndex);
using var cts = new CancellationTokenSource(s_timeout);
await using IAsyncEnumerator<AssetAlarmRecord> alarms = amb
.ObserveHealthAlarmsAsync(cancellationToken: cts.Token)
.GetAsyncEnumerator(cts.Token);
AssetAlarmRecord raised = await NextAsync(
alarms,
async () => await fieldbus.RaiseAsync(
700,
new LocalizedText("The fieldbus is down."),
[AssetRootCauses.Of(cable, new LocalizedText("Cable cut"))],
cts.Token).ConfigureAwait(false),
record => record.IsActive,
cts.Token).ConfigureAwait(false);
DeviceHealthEnumeration? derived = await amb.ReadDeviceHealthAsync(plant.Pump.NodeId).ConfigureAwait(false);
await amb.AcknowledgeAsync(raised.ConditionId, raised.EventId, new LocalizedText("seen"), cts.Token)
.ConfigureAwait(false);
AssetAlarmRecord acknowledged = await NextAsync(
alarms,
() => Task.CompletedTask,
record => record.IsAcknowledged,
cts.Token).ConfigureAwait(false);
await fieldbus.ClearAsync(cancellationToken: cts.Token).ConfigureAwait(false);
AssetAlarmRecord cleared = await NextAsync(
alarms,
() => Task.CompletedTask,
record => !record.IsActive,
cts.Token).ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(raised.SourceNode, Is.EqualTo(plant.Pump.NodeId));
Assert.That(raised.SourceName, Is.EqualTo("Pump"));
Assert.That(raised.Severity, Is.EqualTo((ushort)700));
Assert.That(raised.FaultCategory, Is.EqualTo(AssetFaultSeverity.MajorRecoverableFault));
Assert.That(raised.ConditionClass, Is.SameAs(AmbConditionClass.ConnectionFailure));
Assert.That(raised.Message.Text, Is.EqualTo("The fieldbus is down."));
Assert.That(raised.PotentialRootCauses.Count, Is.EqualTo(1));
Assert.That(raised.PotentialRootCauses[0].RootCauseId, Is.EqualTo(cable));
Assert.That(
raised.EventType,
Is.EqualTo(new NodeId("AssetFailureAlarmType", plant.Server.Manager.TypeNamespaceIndex)));
Assert.That(derived, Is.EqualTo(DeviceHealthEnumeration.FAILURE));
Assert.That(acknowledged.IsActive, Is.True);
Assert.That(cleared.Retain, Is.False, "acknowledged and cleared");
});
}
[Test]
public async Task AConditionRefreshFindsTheConditionsOfAnAssetAsync()
{
await using Plant plant = await Plant
.StartAsync(nameof(AConditionRefreshFindsTheConditionsOfAnAssetAsync), null)
.ConfigureAwait(false);
await using Connection connection = await Connection.OpenAsync(plant.Server, "refresh")
.ConfigureAwait(false);
AmbClient amb = connection.Client;
IAssetHandle pump = plant.Pump!;
IAssetHealthAlarm bearing = pump.Health!.Alarms[0];
await bearing.RaiseAsync(450, new LocalizedText("Bearing hot")).ConfigureAwait(false);
List<Variant[]> refreshed = await amb.RefreshConditionsAsync(pump.NodeId, CancellationToken.None)
.ConfigureAwait(false);
HashSet<NodeId> classes = await amb.MaintenanceClassesAsync(CancellationToken.None).ConfigureAwait(false);
AssetAlarmRecord[] alarms =
[
.. refreshed
.Where(values => !AmbConditionFields.IsMaintenance(values, classes))
.Select(values => AmbConditionFields.ToAlarm(values, amb.Session.MessageContext))
];
MaintenanceActivityRecord[] activities =
[
.. refreshed
.Where(values => AmbConditionFields.IsMaintenance(values, classes))
.Select(values => AmbConditionFields.ToMaintenance(values, amb.Session.MessageContext))
];
Assert.Multiple(() =>
{
Assert.That(alarms.Select(alarm => alarm.ConditionName), Does.Contain(bearing.Name));
Assert.That(alarms.All(alarm => alarm.SourceNode == pump.NodeId), Is.True);
Assert.That(activities, Is.Not.Empty, "the planned activity is retained");
Assert.That(activities[0].State, Is.EqualTo(MaintenanceStateKind.Planned));
});
}
[Test]
public async Task TheClientFollowsAMaintenanceActivityAsync()
{
await using Plant plant = await Plant.StartAsync(nameof(TheClientFollowsAMaintenanceActivityAsync), null)
.ConfigureAwait(false);
await using Connection connection = await Connection.OpenAsync(plant.Server, "maintenance")
.ConfigureAwait(false);
AmbClient amb = connection.Client;
IMaintenanceActivity inspection = plant.Pump!.Maintenance!.Activities[0];
using var cts = new CancellationTokenSource(s_timeout);
await using IAsyncEnumerator<MaintenanceActivityRecord> activities = amb
.ObserveMaintenanceAsync(cancellationToken: cts.Token)
.GetAsyncEnumerator(cts.Token);
MaintenanceActivityRecord planned = await NextAsync(
activities,
async () => await inspection
.UpdateAsync(details => details.EstimatedDowntime = TimeSpan.FromHours(3), default, cts.Token)
.ConfigureAwait(false),
record => record.State == MaintenanceStateKind.Planned,
cts.Token).ConfigureAwait(false);
await inspection.StartAsync(cancellationToken: cts.Token).ConfigureAwait(false);
MaintenanceActivityRecord executing = await NextAsync(
activities,
() => Task.CompletedTask,
record => record.State == MaintenanceStateKind.Executing,
cts.Token).ConfigureAwait(false);
await inspection.FinishAsync(new LocalizedText("No findings."), cts.Token).ConfigureAwait(false);
MaintenanceActivityRecord finished = await NextAsync(
activities,
() => Task.CompletedTask,
record => record.State == MaintenanceStateKind.Finished,
cts.Token).ConfigureAwait(false);
await amb.AcknowledgeAsync(finished.ConditionId, finished.EventId, new LocalizedText("done"), cts.Token)
.ConfigureAwait(false);
MaintenanceActivityRecord acknowledged = await NextAsync(
activities,
() => Task.CompletedTask,
record => record.IsAcknowledged,
cts.Token).ConfigureAwait(false);
ArrayOf<MaintenanceActivityRecord> read = await amb.ReadMaintenanceActivitiesAsync(plant.Pump.NodeId)
.ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(planned.ConditionName, Is.EqualTo("AnnualInspection"));
Assert.That(planned.PlannedDate, Is.EqualTo(s_planned));
Assert.That(planned.EstimatedDowntime, Is.EqualTo(TimeSpan.FromHours(3)));
Assert.That(planned.IsActive, Is.True);
Assert.That(executing.IsActive, Is.True);
Assert.That(finished.IsActive, Is.False);
Assert.That(finished.Message.Text, Is.EqualTo("No findings."));
Assert.That(finished.Retain, Is.True, "retained until acknowledged");
Assert.That(acknowledged.Retain, Is.False);
Assert.That(read[0].State, Is.EqualTo(MaintenanceStateKind.Finished));
Assert.That(read[0].IsAcknowledged, Is.True);
});
}
[Test]
public async Task LinksAndTheAssetIdSurviveARestartAsync()
{
string state = Path.Combine(
TestContext.CurrentContext.WorkDirectory,
nameof(AmbClientServerE2eTests),
Guid.NewGuid().ToString("N"));
const string name = nameof(LinksAndTheAssetIdSurviveARestartAsync);
NodeId added;
await using (Plant first = await Plant.StartAsync(name, state).ConfigureAwait(false))
{
await using Connection connection = await Connection.OpenAsync(first.Server, "first")
.ConfigureAwait(false);
AmbClient amb = connection.Client;
NodeId pump = first.Pump!.NodeId;
added = await amb.AddDocumentationLinkAsync(
pump,
"https://plant.example/wiring",
new QualifiedName("Wiring", first.Server.Manager.InstanceNamespaceIndex),
new LocalizedText("Wiring diagram")).ConfigureAwait(false);
ArrayOf<DocumentationLinkRecord> links = await amb.ReadDocumentationLinksAsync(pump)
.ConfigureAwait(false);
Assert.That(
ListOf(links).Where(link => link.IsUserLink).Select(link => link.NodeId),
Is.EqualTo([added]),
"only the link added through AddLink is a user link");
await amb.WriteDocumentationLinkAsync(
ListOf(links).Single(link => link.BrowseName.Name == "Handbook").NodeId,
"https://plant.example/handbook").ConfigureAwait(false);
await amb.WriteAssetIdAsync(pump, "P-42").ConfigureAwait(false);
ServiceResultException manual = Assert.ThrowsAsync<ServiceResultException>(
async () => await amb.RemoveDocumentationLinkAsync(
pump,
ListOf(links).Single(link => link.BrowseName.Name == "Manual").NodeId).ConfigureAwait(false))!;
Assert.That(manual.StatusCode, Is.EqualTo(StatusCodes.BadInvalidArgument));
}
await using Plant second = await Plant.StartAsync(name, state).ConfigureAwait(false);
await using Connection reconnected = await Connection.OpenAsync(second.Server, "second")
.ConfigureAwait(false);
AmbClient client = reconnected.Client;
NodeId restarted = second.Pump!.NodeId;
ArrayOf<DocumentationLinkRecord> restored = await client.ReadDocumentationLinksAsync(restarted)
.ConfigureAwait(false);
ArrayOf<AssetAlias> byAssetId = await client.FindAssetsAsync("P-42", AssetAliasCategory.ByAssetId)
.ConfigureAwait(false);
await client.RemoveDocumentationLinkAsync(restarted, added).ConfigureAwait(false);
ArrayOf<DocumentationLinkRecord> afterRemoval = await client.ReadDocumentationLinksAsync(restarted)
.ConfigureAwait(false);
ArrayOf<DocumentationLinkRecord> withoutAddIn = await client
.ReadDocumentationLinksAsync(second.Motor!.NodeId)
.ConfigureAwait(false);
ServiceResultException noAddIn = Assert.ThrowsAsync<ServiceResultException>(
async () => await client.AddDocumentationLinkAsync(
second.Motor!.NodeId,
"https://x",
new QualifiedName("X")).ConfigureAwait(false))!;
Assert.Multiple(() =>
{
Assert.That(
ListOf(restored).Single(link => link.NodeId == added).Uri,
Is.EqualTo("https://plant.example/wiring"),
"the added link keeps its NodeId");
Assert.That(
ListOf(restored).Single(link => link.NodeId == added).IsUserLink,
Is.True,
"and stays a user link");
Assert.That(ListOf(afterRemoval).Select(link => link.IsUserLink), Has.All.False);
Assert.That(withoutAddIn.Count, Is.Zero, "an asset without the AddIn has no links");
Assert.That(
ListOf(restored).Single(link => link.BrowseName.Name == "Handbook").Uri,
Is.EqualTo("https://plant.example/handbook"));
Assert.That(byAssetId.Count, Is.EqualTo(1));
Assert.That(afterRemoval.Count, Is.EqualTo(2));
Assert.That(noAddIn.StatusCode, Is.EqualTo(StatusCodes.BadNotSupported));
});
}
[Test]
public async Task AMachineryMachineIsAnAssetAsync()
{
IMachineHandle<BaseObjectState>? machine = null;
IAssetHandle? asset = null;
await using AmbHostedServer server = await AmbHostedServer.StartAsync(
nameof(AMachineryMachineIsAnAssetAsync),
builder => builder
.AddMachinery()
.AddAssetManagement()
.ConfigureMachinery(async context =>
{
machine = await context
.AddMachine(new QualifiedName("Press"))
.WithIdentification(identification =>
{
identification.Manufacturer = new LocalizedText("Acme");
identification.SerialNumber = "SN-1";
identification.ProductInstanceUri = "urn:acme:press:1";
})
.BuildAsync(context.CancellationToken)
.ConfigureAwait(false);
})
.ConfigureDevicesFor<MachineryNodeManager>(async context =>
{
asset = await context.GetRequiredService<IAssetManagement>().RegisterAssetAsync(
machine!.AsNode(),
builder => builder.WithConfigurableAssetId("PRESS-1"),
context.CancellationToken).ConfigureAwait(false);
})).ConfigureAwait(false);
await using Connection connection = await Connection.OpenAsync(server, "machinery").ConfigureAwait(false);
AmbClient amb = connection.Client;
ArrayOf<NodeId> assets = await amb.DiscoverAssetsAsync().ConfigureAwait(false);
AssetIdentificationRecord identification = await amb.ReadIdentificationAsync(asset!.NodeId)
.ConfigureAwait(false);
await amb.WriteAssetIdAsync(asset.NodeId, "PRESS-2").ConfigureAwait(false);
ArrayOf<AssetAlias> moved = await amb.FindAssetsAsync("PRESS-2", AssetAliasCategory.ByAssetId)
.ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(assets.ToArray(), Is.EqualTo(new[] { asset.NodeId }));
Assert.That(identification.ProductInstanceUri, Is.EqualTo("urn:acme:press:1"));
Assert.That(identification.SerialNumber, Is.EqualTo("SN-1"));
Assert.That(identification.Manufacturer.Text, Is.EqualTo("Acme"));
Assert.That(identification.AssetId, Is.EqualTo("PRESS-1"));
Assert.That(moved.Count, Is.EqualTo(1));
Assert.That(
server.Manager.ConformanceUnits.ToArray(),
Does.Contain(new QualifiedName("AMB Asset Identification")),
"the machine publishes its ProductInstanceUri in its Identification group");
});
}
/// <summary>
/// Reads stream entries, poking the server until one matches: an event
/// stream says nothing until its monitored item is up, so the poke
/// repeats until the first matching event arrives.
/// </summary>
/// <typeparam name="T">The type of the stream entries.</typeparam>
private static async Task<T> NextAsync<T>(
IAsyncEnumerator<T> stream,
Func<Task> poke,
Func<T, bool> match,
CancellationToken cancellationToken)
{
Task<bool> next = stream.MoveNextAsync().AsTask();
while (true)
{
Task done = await Task.WhenAny(next, Task.Delay(500, cancellationToken)).ConfigureAwait(false);
if (done == next)
{
Assert.That(await next.ConfigureAwait(false), Is.True, "the stream ended");
if (match(stream.Current))
{
return stream.Current;
}
next = stream.MoveNextAsync().AsTask();
continue;
}
cancellationToken.ThrowIfCancellationRequested();
await poke().ConfigureAwait(false);
}
}
private static List<T> ListOf<T>(ArrayOf<T> items)
{
var list = new List<T>(items.Count);
foreach (T item in items)
{
list.Add(item);
}
return list;
}
private static async Task<DataValue> ReadAsync(ManagedSession session, NodeId nodeId)
{
ReadResponse response = await session.ReadAsync(
null,
0,
TimestampsToReturn.Neither,
[new ReadValueId { NodeId = nodeId, AttributeId = Attributes.Value }],
CancellationToken.None).ConfigureAwait(false);
return response.Results[0];
}
/// <summary>
/// A hosted server with three Device Integration devices: a motor, a
/// pump that contains it and uses every AMB building block, and a
/// sensor that utilizes the pump.
/// </summary>
private sealed class Plant : IAsyncDisposable
{
private Plant(AmbHostedServer server)
{
Server = server;
}
public AmbHostedServer Server { get; }
public IAssetHandle? Motor { get; private set; }
public IAssetHandle? Pump { get; private set; }
public IAssetHandle? Sensor { get; private set; }
public static async Task<Plant> StartAsync(string name, string? state)
{
IAssetHandle? motor = null;
IAssetHandle? pump = null;
IAssetHandle? sensor = null;
AmbHostedServer server = await AmbHostedServer.StartAsync(
name,
builder => builder
.AddOpcUaDi()
.AddAssetManagement(options =>
{
// AddLink needs a persistent store (§10.5.3).
options.UseFileSystemStores(state ??
Path.Combine(
TestContext.CurrentContext.WorkDirectory,
nameof(AmbClientServerE2eTests),
Guid.NewGuid().ToString("N")));
options.AuthorizeLinkEdit = _ => true;
})
.ConfigureDevicesFor<DiNodeManager>(async context =>
{
IAssetManagement assets = context.GetRequiredService<IAssetManagement>();
IDeviceBuilder<DeviceState> motorDevice = await AssetRegistrationTests
.CreateDeviceAsync(context, "Motor", MotorUri).ConfigureAwait(false);
motor = await motorDevice.RegisterAsAssetAsync(assets).ConfigureAwait(false);
IDeviceBuilder<DeviceState> pumpDevice = await AssetRegistrationTests
.CreateDeviceAsync(context, "Pump", PumpUri).ConfigureAwait(false);
pump = await pumpDevice.RegisterAsAssetAsync(
assets,
asset => asset
.WithConfigurableAssetId("P-1")
.WithDeviceHealth(deriveFromAlarms: true)
.WithHealthAlarm(
"Fieldbus",
AssetHealthAlarmKind.Failure,
AmbConditionClass.ConnectionFailure)
.WithMaintenance(
"AnnualInspection",
AmbConditionClass.Inspection,
details =>
{
details.Description = new LocalizedText("Annual inspection.");
details.PlannedDate = s_planned;
})
.WithDocumentationLinks(links => links
.Add("Manual", "https://acme.example/pump/manual.pdf")
.AddEditable("Handbook")
.AllowUserLinks())
.WithVersionInformation("HW-1", "SW-1", 1)
.LocatedIn(AssetLocationKind.Hierarchical, "Plant1/Hall3/Line2")
.WithLocation(AssetLocationKind.Hierarchical, "Plant1/Hall3/Line2")
.WithLocalTime(60)
.ClassifiedAs(s_eclass)
.WithRequirements(requirements => requirements
.Add("SupplyVoltage", Variant.From(24.0)))
.RelatesTo(Ua.ReferenceTypeIds.HasComponent, motor.NodeId),
context.CancellationToken).ConfigureAwait(false);
IDeviceBuilder<DeviceState> sensorDevice = await AssetRegistrationTests
.CreateDeviceAsync(context, "Sensor", SensorUri).ConfigureAwait(false);
sensor = await sensorDevice.RegisterAsAssetAsync(
assets,
asset => asset.RelatesTo(Ua.ReferenceTypeIds.Utilizes, pump.NodeId),
context.CancellationToken).ConfigureAwait(false);
})).ConfigureAwait(false);
return new Plant(server) { Motor = motor, Pump = pump, Sensor = sensor };
}
public ValueTask DisposeAsync()
{
return Server.DisposeAsync();
}
}
/// <summary>
/// A managed session with the AMB client on it.
/// </summary>
private sealed class Connection : IAsyncDisposable
{
private Connection(ClientFixture fixture, ManagedSession session, AmbClient client)
{
m_fixture = fixture;
Session = session;
Client = client;
}
public ManagedSession Session { get; }
public AmbClient Client { get; }
public static async Task<Connection> OpenAsync(AmbHostedServer server, string name)
{
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
var fixture = new ClientFixture(telemetry);
await fixture.LoadClientConfigurationAsync(Path.Combine(
TestContext.CurrentContext.WorkDirectory,
nameof(AmbClientServerE2eTests),
Guid.NewGuid().ToString("N"),
"client-pki")).ConfigureAwait(false);
EndpointDescription? endpoint = await CoreClientUtils.SelectEndpointAsync(
fixture.Config,
server.EndpointUrl,
useSecurity: false,
discoverTimeout: 15000,
telemetry).ConfigureAwait(false);
Assert.That(endpoint, Is.Not.Null);
ManagedSession session = await new ManagedSessionBuilder(fixture.Config, telemetry)
.UseEndpoint(new ConfiguredEndpoint(null, endpoint, EndpointConfiguration.Create(fixture.Config)))
.WithSessionName(name)
.ConnectAsync().ConfigureAwait(false);
return new Connection(fixture, session, session.AssetManagement(telemetry));
}
public async ValueTask DisposeAsync()
{
try
{
await Session.DisposeAsync().ConfigureAwait(false);
}
finally
{
m_fixture.Dispose();
}
}
private readonly ClientFixture m_fixture;
}
}
}