Files
UA-.NETStandard/tests/Opc.Ua.AMB.Tests/AssetStructureTests.cs
Klaus Landsdorf 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

839 lines
43 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.Tasks;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Opc.Ua.AMB.Server;
using Opc.Ua.AMB.Server.Assets;
using Opc.Ua.AMB.Server.Hosting;
using Opc.Ua.AMB.Server.Structure;
using Opc.Ua.Di;
using Opc.Ua.Di.Server;
using Opc.Ua.Di.Server.Builders;
using Opc.Ua.Server.Fluent;
namespace Opc.Ua.AMB.Tests
{
/// <summary>
/// Gives registered assets their version information, locations,
/// classification, requirements, capabilities and relations
/// (OPC 10000-110 §10, §11, §13, §14) in a hosted server.
/// </summary>
[TestFixture]
[Category("AMB")]
[Category("Hosting")]
[NonParallelizable]
public sealed class AssetStructureTests
{
private static readonly QualifiedName[] s_locationUnits =
[
new("AMB Hierarchical Location Property"),
new("AMB Hierarchical Location Objects"),
new("AMB Operational Location Property"),
new("AMB Operational Location Objects"),
new("AMB Digital Location")
];
private static readonly QualifiedName[] s_classificationUnits =
[
new("AMB Requirements"),
new("AMB Capabilities"),
new("AMB Local Time")
];
private static readonly QualifiedName[] s_structureUnits =
[
new("AMB Sub-assets"),
new("AMB Asset relations"),
new("AMB Operation Counters")
];
[TestCase(false, TestName = "LocationsWithDeviceIntegrationRegisteredFirst")]
[TestCase(true, TestName = "LocationsWithAssetManagementRegisteredFirst")]
public async Task LocationsContainTheAssetInBothDirectionsAsync(bool assetManagementFirst)
{
(AmbHostedServer server, IAssetHandle asset, DeviceState device) = await HealthAlarmTests
.StartWithSensorAsync(
nameof(LocationsContainTheAssetInBothDirectionsAsync) + assetManagementFirst,
builder => builder
.LocatedIn(AssetLocationKind.Hierarchical, "Plant1/Hall3/Line2")
.LocatedIn(AssetLocationKind.Operational, "Packaging")
.WithLocation(AssetLocationKind.Hierarchical, "Plant1/Hall3/Line2")
.WithLocation(AssetLocationKind.Operational, "Packaging")
.WithLocation(AssetLocationKind.Digital, "https://plant1.example/sensor"),
assetManagementFirst: assetManagementFirst)
.ConfigureAwait(false);
await using AmbHostedServer serverScope = server;
ushort instances = server.Manager.InstanceNamespaceIndex;
NodeId hierarchicalContains = server.ToNodeId(ReferenceTypeIds.HierarchicalContains);
NodeId operationalContains = server.ToNodeId(ReferenceTypeIds.OperationalContains);
IReadOnlyList<ReferenceDescription> roots = await server
.BrowseAsync(server.ToNodeId(ObjectIds.HierarchicalLocations), Ua.ReferenceTypeIds.Organizes)
.ConfigureAwait(false);
NodeId plant = server.ToNodeId(roots.Single(reference => reference.BrowseName.Name == "Plant1").NodeId);
NodeId hall = await ChildAsync(server, plant, "Hall3").ConfigureAwait(false);
NodeId line = await ChildAsync(server, hall, "Line2").ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> contained = await server
.BrowseAsync(line, hierarchicalContains)
.ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> locatedIn = await server
.BrowseAsync(device.NodeId, hierarchicalContains, BrowseDirection.Inverse)
.ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> operational = await server
.BrowseAsync(device.NodeId, operationalContains, BrowseDirection.Inverse)
.ConfigureAwait(false);
NodeId again = await server.AssetManagement
.DefineLocationAsync(AssetLocationKind.Hierarchical, " Plant1 / Hall3 / Line2 ")
.ConfigureAwait(false);
DataValue digital = await server
.ReadAsync(Child(server, device, Amb(server, "DigitalLocation")))
.ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(
roots.Single(reference => reference.BrowseName.Name == "Plant1").BrowseName.NamespaceIndex,
Is.EqualTo(instances));
Assert.That(
contained.Select(reference => reference.NodeId),
Does.Contain((ExpandedNodeId)device.NodeId));
Assert.That(locatedIn.Select(reference => reference.NodeId), Does.Contain((ExpandedNodeId)line));
Assert.That(operational, Has.Count.EqualTo(1));
Assert.That(again, Is.EqualTo(line), "an existing path is found again");
Assert.That(digital.WrappedValue.TryGetValue(out string uri) ? uri : null, Is.EqualTo(
"https://plant1.example/sensor"));
Assert.That(server.Manager.ConformanceUnits.ToArray(), Is.SupersetOf(s_locationUnits));
});
}
[Test]
public async Task AnUnregisteredAssetLeavesItsLocationsAsync()
{
(AmbHostedServer server, IAssetHandle asset, DeviceState device) = await HealthAlarmTests
.StartWithSensorAsync(
nameof(AnUnregisteredAssetLeavesItsLocationsAsync),
builder => builder
.LocatedIn(AssetLocationKind.Hierarchical, "Plant1/Hall3")
.LocatedIn(AssetLocationKind.Operational, "Cooling"))
.ConfigureAwait(false);
await using AmbHostedServer serverScope = server;
NodeId hierarchicalContains = server.ToNodeId(ReferenceTypeIds.HierarchicalContains);
NodeId operationalContains = server.ToNodeId(ReferenceTypeIds.OperationalContains);
NodeId hall = await server.AssetManagement
.DefineLocationAsync(AssetLocationKind.Hierarchical, "Plant1/Hall3")
.ConfigureAwait(false);
NodeId cooling = await server.AssetManagement
.DefineLocationAsync(AssetLocationKind.Operational, "Cooling")
.ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> before = await server
.BrowseAsync(hall, hierarchicalContains)
.ConfigureAwait(false);
await asset.UnregisterAsync().ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> hierarchical = await server
.BrowseAsync(hall, hierarchicalContains)
.ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> operational = await server
.BrowseAsync(cooling, operationalContains)
.ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> locatedIn = await server
.BrowseAsync(device.NodeId, hierarchicalContains, BrowseDirection.Inverse)
.ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(before, Has.Count.EqualTo(1));
Assert.That(hierarchical, Is.Empty, "the location no longer contains the asset");
Assert.That(operational, Is.Empty);
Assert.That(locatedIn, Is.Empty, "nor is the object located in it");
});
}
[Test]
public async Task VersionInformationUsesTheDeviceSlotsAsync()
{
(AmbHostedServer server, IAssetHandle asset, DeviceState device) = await HealthAlarmTests
.StartWithSensorAsync(
nameof(VersionInformationUsesTheDeviceSlotsAsync),
builder => builder.WithVersionInformation("HW-1", "SW-2", 3))
.ConfigureAwait(false);
await using AmbHostedServer serverScope = server;
int next = await asset.IncrementRevisionCounterAsync().ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(device.HardwareRevision?.Value, Is.EqualTo("HW-1"));
Assert.That(device.SoftwareRevision?.Value, Is.EqualTo("SW-2"));
Assert.That(device.RevisionCounter?.Value, Is.EqualTo(4));
Assert.That(next, Is.EqualTo(4));
Assert.That(
server.Manager.ConformanceUnits.ToArray(),
Does.Contain(new QualifiedName("AMB Version Information")));
});
}
[Test]
public async Task TheDeviceIntegrationDefaultsAreNoVersionInformationAsync()
{
(AmbHostedServer withoutVersion, DeviceState? first) = await StartWithRevisionsAsync(
nameof(TheDeviceIntegrationDefaultsAreNoVersionInformationAsync) + "Without",
askForVersionInformation: false).ConfigureAwait(false);
await using AmbHostedServer withoutScope = withoutVersion;
(AmbHostedServer withVersion, DeviceState? second) = await StartWithRevisionsAsync(
nameof(TheDeviceIntegrationDefaultsAreNoVersionInformationAsync) + "With",
askForVersionInformation: true).ConfigureAwait(false);
await using AmbHostedServer withScope = withVersion;
Assert.Multiple(() =>
{
Assert.That(first!.RevisionCounter?.Value, Is.EqualTo(-1));
Assert.That(
withoutVersion.Manager.ConformanceUnits.ToArray(),
Does.Not.Contain(new QualifiedName("AMB Version Information")),
"a RevisionCounter of -1 says the asset does not support it");
Assert.That(second!.RevisionCounter?.Value, Is.Zero, "asking for version information starts it");
Assert.That(
withVersion.Manager.ConformanceUnits.ToArray(),
Does.Contain(new QualifiedName("AMB Version Information")));
});
}
private static async Task<(AmbHostedServer Server, DeviceState? Device)> StartWithRevisionsAsync(
string name,
bool askForVersionInformation)
{
DeviceState? device = null;
AmbHostedServer server = await AmbHostedServer.StartAsync(
name,
builder => builder
.AddOpcUaDi()
.AddAssetManagement()
.ConfigureDevicesFor<DiNodeManager>(async context =>
{
IDeviceBuilder<DeviceState> sensor = await AssetRegistrationTests.CreateDeviceAsync(
context,
"Sensor",
"urn:acme:sensor").ConfigureAwait(false);
sensor.WithIdentification(identification =>
{
identification.HardwareRevision = "C";
identification.RevisionCounter = -1;
});
device = sensor.Device;
await sensor.RegisterAsAssetAsync(
context.GetRequiredService<IAssetManagement>(),
asset =>
{
if (askForVersionInformation)
{
asset.WithVersionInformation();
}
}).ConfigureAwait(false);
})).ConfigureAwait(false);
return (server, device);
}
[Test]
public async Task VersionInformationIsCreatedOnAnyObjectAsync()
{
IAssetHandle? bare = null;
IAssetHandle? software = null;
INodeBuilder<BaseObjectState>? softwareNode = null;
await using AmbHostedServer server = await AmbHostedServer.StartAsync(
nameof(VersionInformationIsCreatedOnAnyObjectAsync),
builder => builder
.AddOpcUaDi()
.AddAssetManagement()
.ConfigureAssetManagement(async context =>
{
bare = await context.Assets.RegisterAssetAsync(
AssetRegistrationTests.CreateMachine(context, "urn:acme:press:1"),
null,
context.CancellationToken).ConfigureAwait(false);
softwareNode = CreatePart(context, null, "Firmware", "urn:acme:firmware:3");
software = await context.Assets.RegisterAssetAsync(
softwareNode,
asset => asset.WithVersionInformation(softwareRevision: "3.1.4"),
context.CancellationToken).ConfigureAwait(false);
})).ConfigureAwait(false);
ServiceResultException refused = Assert.ThrowsAsync<ServiceResultException>(
async () => await bare!.IncrementRevisionCounterAsync().ConfigureAwait(false))!;
int next = await software!.IncrementRevisionCounterAsync().ConfigureAwait(false);
ushort di = (ushort)server.Server.NamespaceUris.GetIndex(Opc.Ua.Di.Namespaces.OpcUaDi);
BaseObjectState firmware = softwareNode!.Node;
Assert.Multiple(() =>
{
Assert.That(refused.StatusCode, Is.EqualTo(StatusCodes.BadInvalidState));
Assert.That(next, Is.EqualTo(1), "a created counter starts at 0");
Assert.That(
((BaseVariableState)firmware.FindChildWithQualifiedName(
server.Manager.SystemContext,
new QualifiedName("SoftwareRevision", di))!).WrappedValue.TryGetValue(out string revision)
? revision
: null,
Is.EqualTo("3.1.4"));
Assert.That(
firmware.FindChildWithQualifiedName(
server.Manager.SystemContext,
new QualifiedName("HardwareRevision", di)),
Is.Null,
"§10.2: a software asset has no hardware revision");
Assert.That(
firmware.ReferenceExists(
Ua.ReferenceTypeIds.HasInterface,
false,
server.ToNodeId(Opc.Ua.Di.ObjectTypeIds.IVendorNameplateType)),
Is.True);
Assert.That(
server.Manager.ConformanceUnits.ToArray(),
Does.Not.Contain(new QualifiedName("AMB Version Information")),
"the bare machine has none");
});
}
[Test]
public async Task WritableLocationsAndLocalTimeSurviveARestartAsync()
{
string state = Path.Combine(
TestContext.CurrentContext.WorkDirectory,
nameof(AssetStructureTests),
Guid.NewGuid().ToString("N"));
const string name = nameof(WritableLocationsAndLocalTimeSurviveARestartAsync);
await using (AmbHostedServer first = await StartWithStoreAsync(name, state).ConfigureAwait(false))
{
BaseObjectState sensor = await first
.FindNodeAsync<BaseObjectState>(first.AssetManagement.Assets[0].NodeId)
.ConfigureAwait(false);
NodeId location = Child(first, sensor, Amb(first, "HierarchicalLocation"));
NodeId localTime = Child(first, sensor, new QualifiedName("LocalTime"));
StatusCode written = await first.WriteAsync(location, Variant.From("Plant2/Hall1"))
.ConfigureAwait(false);
StatusCode wrongType = await first.WriteAsync(location, Variant.From(7)).ConfigureAwait(false);
StatusCode tooLong = await first.WriteAsync(location, Variant.From(new string('p', 1025)))
.ConfigureAwait(false);
StatusCode timeZone = await first
.WriteAsync(localTime, Variant.FromStructure(new TimeZoneDataType { Offset = 120 }))
.ConfigureAwait(false);
StatusCode notATimeZone = await first.WriteAsync(localTime, Variant.From("UTC+2"))
.ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(written, Is.EqualTo(StatusCodes.Good));
Assert.That(wrongType, Is.EqualTo(StatusCodes.BadTypeMismatch));
Assert.That(tooLong, Is.EqualTo(StatusCodes.BadOutOfRange), "MaxLocationLength");
Assert.That(timeZone, Is.EqualTo(StatusCodes.Good));
Assert.That(notATimeZone, Is.EqualTo(StatusCodes.BadTypeMismatch));
});
}
await using AmbHostedServer second = await StartWithStoreAsync(name, state).ConfigureAwait(false);
BaseObjectState restarted = await second
.FindNodeAsync<BaseObjectState>(second.AssetManagement.Assets[0].NodeId)
.ConfigureAwait(false);
DataValue restoredLocation = await second
.ReadAsync(Child(second, restarted, Amb(second, "HierarchicalLocation")))
.ConfigureAwait(false);
DataValue restoredTime = await second
.ReadAsync(Child(second, restarted, new QualifiedName("LocalTime")))
.ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(
restoredLocation.WrappedValue.TryGetValue(out string text) ? text : null,
Is.EqualTo("Plant2/Hall1"));
Assert.That(TimeZoneOf(restoredTime)?.Offset, Is.EqualTo((short)120));
Assert.That(TimeZoneOf(restoredTime)?.DaylightSavingInOffset, Is.False);
});
}
[Test]
public async Task ClassificationRequirementsAndCapabilitiesAsync()
{
var eclass = new ExpandedNodeId("0173-1#01-ADN228#012", "urn:example:eclass");
var voltage = new ExpandedNodeId("0173-1#02-AAC967#005", "urn:example:eclass");
(AmbHostedServer server, IAssetHandle asset, DeviceState device) = await HealthAlarmTests
.StartWithSensorAsync(
nameof(ClassificationRequirementsAndCapabilitiesAsync),
builder => builder
.ClassifiedAs(eclass)
.WithLocalTime(60, daylightSavingInOffset: true)
.WithRequirements(requirements => requirements
.Add("SupplyVoltage", Variant.From(24.0), voltage))
.WithCapabilities(capabilities => capabilities
.Add("MaxPressure", Variant.From(16.0))
.Add("Medium", Variant.From("Water"))))
.ConfigureAwait(false);
await using AmbHostedServer serverScope = server;
ushort amb = server.Manager.AmbNamespaceIndex;
var requirements = (FolderState)device.FindChildWithQualifiedName(
server.Manager.SystemContext,
new QualifiedName("Requirements", amb))!;
var capabilities = (FolderState)device.FindChildWithQualifiedName(
server.Manager.SystemContext,
new QualifiedName("Capabilities", amb))!;
IReadOnlyList<ReferenceDescription> entries = await server
.BrowseAsync(requirements.NodeId, Ua.ReferenceTypeIds.Organizes)
.ConfigureAwait(false);
NodeId supplyVoltage = server.ToNodeId(entries.Single().NodeId);
BaseVariableState entry = await server.FindNodeAsync<BaseVariableState>(supplyVoltage)
.ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> classified = await server
.BrowseAsync(device.NodeId, Ua.ReferenceTypeIds.HasDictionaryEntry)
.ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> capabilityEntries = await server
.BrowseAsync(capabilities.NodeId, Ua.ReferenceTypeIds.Organizes)
.ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(classified.Select(reference => reference.NodeId), Does.Contain(eclass));
Assert.That(entries.Single().BrowseName.Name, Is.EqualTo("SupplyVoltage"));
Assert.That(entry.DataType, Is.EqualTo(Ua.DataTypeIds.Double));
Assert.That(entry.WrappedValue.TryGetValue(out double value) ? value : 0, Is.EqualTo(24.0));
Assert.That(entry.ReferenceExists(Ua.ReferenceTypeIds.HasDictionaryEntry, false, voltage), Is.True);
Assert.That(capabilityEntries, Has.Count.EqualTo(2));
Assert.That(
device.FindChildWithQualifiedName(server.Manager.SystemContext, new QualifiedName("LocalTime")),
Is.Not.Null);
Assert.That(server.Manager.ConformanceUnits.ToArray(), Is.SupersetOf(s_classificationUnits));
Assert.That(
server.Manager.ConformanceUnits.ToArray(),
Does.Not.Contain(new QualifiedName("AMB Classification")),
"Part 19: the target is no dictionary entry object of the server");
});
}
[Test]
public async Task AClassificationNeedsADictionaryEntryObjectAsync()
{
const string irdi = "0173-1#01-AKE798#019";
var classification = new ExpandedNodeId(irdi, AmbServerOptions.IrdiNamespaceUri);
NodeId entry = NodeId.Null;
DeviceState? device = null;
await using AmbHostedServer server = await AmbHostedServer.StartAsync(
nameof(AClassificationNeedsADictionaryEntryObjectAsync),
builder => builder
.AddOpcUaDi()
.AddAssetManagement()
.ConfigureAssetManagement(async context =>
{
entry = await context.Assets
.DefineDictionaryEntryAsync(irdi, new LocalizedText("Centrifugal pump"))
.ConfigureAwait(false);
NodeId again = await context.Assets.DefineDictionaryEntryAsync(irdi).ConfigureAwait(false);
Assert.That(again, Is.EqualTo(entry), "an entry is defined once");
})
.ConfigureDevicesFor<DiNodeManager>(async context =>
{
IDeviceBuilder<DeviceState> pump = await AssetRegistrationTests.CreateDeviceAsync(
context,
"Pump",
"urn:acme:pump:1").ConfigureAwait(false);
device = pump.Device;
await pump.RegisterAsAssetAsync(
context.GetRequiredService<IAssetManagement>(),
asset => asset.ClassifiedAs(classification)).ConfigureAwait(false);
})).ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> dictionaries = await server
.BrowseAsync(Ua.ObjectIds.Dictionaries, Ua.ReferenceTypeIds.HasComponent)
.ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> classified = await server
.BrowseAsync(device!.NodeId, Ua.ReferenceTypeIds.HasDictionaryEntry)
.ConfigureAwait(false);
ReferenceDescription? listed = dictionaries.FirstOrDefault(
reference => server.ToNodeId(reference.NodeId) == entry);
Assert.Multiple(() =>
{
Assert.That(entry.IdType, Is.EqualTo(IdType.String));
Assert.That(
server.Server.NamespaceUris.GetString(entry.NamespaceIndex),
Is.EqualTo(AmbServerOptions.IrdiNamespaceUri));
Assert.That(listed, Is.Not.Null, "the entry is a component of Server/Dictionaries");
Assert.That(
listed?.TypeDefinition,
Is.EqualTo((ExpandedNodeId)Ua.ObjectTypeIds.IrdiDictionaryEntryType));
Assert.That(classified.Select(reference => server.ToNodeId(reference.NodeId)), Does.Contain(entry));
Assert.That(
server.Manager.ConformanceUnits.ToArray(),
Does.Contain(new QualifiedName("AMB Classification")));
});
}
[TestCase(true, TestName = "DictionaryEntryDefinedBeforeTheAsset")]
[TestCase(false, TestName = "DictionaryEntryDefinedAfterTheAsset")]
public async Task ADictionaryEntryListsWhatItClassifiesAsync(bool entryFirst)
{
// The device lives in the Device Integration manager, the entry in
// the AMB manager; which setup runs first follows the order the
// managers are added in.
const string irdi = "0173-1#01-AKE798#019";
var classification = new ExpandedNodeId(irdi, AmbServerOptions.IrdiNamespaceUri);
NodeId entry = NodeId.Null;
bool entryExistedAtRegistration = false;
DeviceState? device = null;
await using AmbHostedServer server = await AmbHostedServer.StartAsync(
nameof(ADictionaryEntryListsWhatItClassifiesAsync) + entryFirst,
builder =>
{
if (entryFirst)
{
builder.AddAssetManagement().AddOpcUaDi();
}
else
{
builder.AddOpcUaDi().AddAssetManagement();
}
builder
.ConfigureAssetManagement(async context =>
{
entry = await context.Assets.DefineDictionaryEntryAsync(irdi).ConfigureAwait(false);
})
.ConfigureDevicesFor<DiNodeManager>(async context =>
{
entryExistedAtRegistration = !entry.IsNull;
IDeviceBuilder<DeviceState> pump = await AssetRegistrationTests.CreateDeviceAsync(
context,
"Pump",
"urn:acme:pump:1").ConfigureAwait(false);
device = pump.Device;
await pump.RegisterAsAssetAsync(
context.GetRequiredService<IAssetManagement>(),
asset => asset
.ClassifiedAs(classification)
.WithRequirements(requirements => requirements
.Add("SupplyVoltage", Variant.From(24.0), classification)))
.ConfigureAwait(false);
});
}).ConfigureAwait(false);
var requirements = (FolderState)device!.FindChildWithQualifiedName(
server.Manager.SystemContext,
Amb(server, "Requirements"))!;
NodeId supplyVoltage = Child(
server,
requirements,
new QualifiedName("SupplyVoltage", device.NodeId.NamespaceIndex));
IReadOnlyList<ReferenceDescription> classified = await server
.BrowseAsync(entry, Ua.ReferenceTypeIds.HasDictionaryEntry, BrowseDirection.Inverse)
.ConfigureAwait(false);
IReadOnlyList<ReferenceDescription> referencedByVoltage = await server
.BrowseAsync(supplyVoltage, Ua.ReferenceTypeIds.HasDictionaryEntry)
.ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(entryExistedAtRegistration, Is.EqualTo(entryFirst));
Assert.That(
classified.Select(reference => server.ToNodeId(reference.NodeId)),
Is.EquivalentTo(new[] { device.NodeId, supplyVoltage }),
"DictionaryEntryOf lists the asset and the requirement");
Assert.That(
referencedByVoltage.Select(reference => server.ToNodeId(reference.NodeId)),
Is.EqualTo(new[] { entry }));
});
}
[Test]
public async Task SubAssetsRelationsAndOperationCountersAsync()
{
IAssetHandle? press = null;
IAssetHandle? drive = null;
IAssetHandle? sensor = null;
await using AmbHostedServer server = await AmbHostedServer.StartAsync(
nameof(SubAssetsRelationsAndOperationCountersAsync),
builder => builder
.AddOpcUaDi()
.AddAssetManagement()
.ConfigureDevicesFor<DiNodeManager>(async context =>
{
IDeviceBuilder<DeviceState> device = await AssetRegistrationTests.CreateDeviceAsync(
context,
"Sensor",
"urn:acme:sensor:4711").ConfigureAwait(false);
sensor = await device.RegisterAsAssetAsync(context.GetRequiredService<IAssetManagement>()).ConfigureAwait(false);
})
.ConfigureAssetManagement(async context =>
{
INodeBuilder<BaseObjectState> machine = AssetRegistrationTests.CreateMachine(
context,
"urn:acme:press:1");
INodeBuilder<BaseObjectState> motor = CreatePart(
context,
machine.Node,
"Drive",
"urn:acme:drive:7");
AddOperationCounter(context, machine.Node);
drive = await context.Assets.RegisterAssetAsync(motor, null, context.CancellationToken).ConfigureAwait(false);
press = await context.Assets.RegisterAssetAsync(
machine,
asset => asset.RelatesTo(Ua.ReferenceTypeIds.Utilizes, sensor!.NodeId),
context.CancellationToken).ConfigureAwait(false);
})).ConfigureAwait(false);
DeviceState sensorNode = await server.FindNodeAsync<DeviceState>(sensor!.NodeId).ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(drive, Is.Not.Null);
Assert.That(
sensorNode.ReferenceExists(Ua.ReferenceTypeIds.Utilizes, true, press!.NodeId),
Is.True,
"the related asset gets the inverse reference");
Assert.That(server.Manager.ConformanceUnits.ToArray(), Is.SupersetOf(s_structureUnits));
});
}
[Test]
public async Task AHierarchicalReferenceMakesASubAssetAsync()
{
IAssetHandle? pump = null;
await using AmbHostedServer server = await AmbHostedServer.StartAsync(
nameof(AHierarchicalReferenceMakesASubAssetAsync),
builder => builder
.AddOpcUaDi()
.AddAssetManagement()
.ConfigureDevicesFor<DiNodeManager>(async context =>
{
IAssetManagement assets = context.GetRequiredService<IAssetManagement>();
IDeviceBuilder<DeviceState> motor = await AssetRegistrationTests.CreateDeviceAsync(
context,
"Motor",
"urn:acme:motor:1").ConfigureAwait(false);
IAssetHandle motorAsset = await motor.RegisterAsAssetAsync(assets).ConfigureAwait(false);
IDeviceBuilder<DeviceState> device = await AssetRegistrationTests.CreateDeviceAsync(
context,
"Pump",
"urn:acme:pump:1").ConfigureAwait(false);
pump = await device.RegisterAsAssetAsync(
assets,
asset => asset.RelatesTo(Ua.ReferenceTypeIds.HasComponent, motorAsset.NodeId)).ConfigureAwait(false);
})).ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(pump, Is.Not.Null);
Assert.That(
server.Manager.ConformanceUnits.ToArray(),
Does.Contain(new QualifiedName("AMB Sub-assets")));
Assert.That(
server.Manager.ConformanceUnits.ToArray(),
Does.Not.Contain(new QualifiedName("AMB Asset relations")),
"a hierarchical reference is no relation");
});
}
[Test]
public async Task InvalidLocationsAreRefusedAsync()
{
await using AmbHostedServer server = await AmbHostedServer.StartAsync(
nameof(InvalidLocationsAreRefusedAsync),
builder => builder.AddOpcUaDi().AddAssetManagement()).ConfigureAwait(false);
var builder = new AssetBuilder();
Assert.Multiple(() =>
{
Assert.ThrowsAsync<ArgumentException>(async () => await server.AssetManagement
.DefineLocationAsync(AssetLocationKind.Digital, "Somewhere")
.ConfigureAwait(false));
Assert.ThrowsAsync<ArgumentException>(async () => await server.AssetManagement
.DefineLocationAsync(AssetLocationKind.Hierarchical, "Plant1//Line2")
.ConfigureAwait(false));
Assert.ThrowsAsync<ArgumentException>(async () => await server.AssetManagement
.DefineLocationAsync(AssetLocationKind.Operational, " ")
.ConfigureAwait(false));
Assert.Throws<ArgumentException>(() => builder.LocatedIn(AssetLocationKind.Digital, "Somewhere"));
Assert.Throws<ArgumentException>(() => builder.LocatedIn(AssetLocationKind.Hierarchical, string.Empty));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.WithLocation((AssetLocationKind)42));
Assert.Throws<ArgumentException>(() => builder.ClassifiedAs(ExpandedNodeId.Null));
Assert.Throws<ArgumentException>(() => builder.RelatesTo(NodeId.Null, new NodeId(1u)));
Assert.Throws<ArgumentException>(() => builder.RelatesTo(Ua.ReferenceTypeIds.Utilizes, NodeId.Null));
Assert.Throws<ArgumentNullException>(() => builder.WithRequirements(null!));
Assert.Throws<ArgumentNullException>(() => builder.WithCapabilities(null!));
Assert.Throws<ArgumentException>(() => builder.WithRequirements(entries => entries
.Add("A", Variant.From(1))
.Add("A", Variant.From(2))));
Assert.Throws<ArgumentException>(() => builder.WithCapabilities(entries => entries
.Add(string.Empty, Variant.From(1))));
Assert.ThrowsAsync<ServiceResultException>(async () => await new AssetManagement()
.DefineLocationAsync(AssetLocationKind.Hierarchical, "Plant1")
.ConfigureAwait(false));
});
}
private static async Task<NodeId> ChildAsync(AmbHostedServer server, NodeId parent, string name)
{
IReadOnlyList<ReferenceDescription> children = await server
.BrowseAsync(parent, Ua.ReferenceTypeIds.HasComponent)
.ConfigureAwait(false);
return server.ToNodeId(children.Single(reference => reference.BrowseName.Name == name).NodeId);
}
private static QualifiedName Amb(AmbHostedServer server, string name)
{
return new QualifiedName(name, server.Manager.AmbNamespaceIndex);
}
private static NodeId Child(AmbHostedServer server, NodeState parent, QualifiedName name)
{
NodeState? child = parent.FindChildWithQualifiedName(server.Manager.SystemContext, name);
Assert.That(child, Is.Not.Null, name.ToString());
return child!.NodeId;
}
private static Task<AmbHostedServer> StartWithStoreAsync(string name, string state)
{
return AmbHostedServer.StartAsync(
name,
builder => builder
.AddOpcUaDi()
.AddAssetManagement(options => options.UseFileSystemStores(state))
.ConfigureDevicesFor<DiNodeManager>(async context =>
{
IDeviceBuilder<DeviceState> device = await AssetRegistrationTests.CreateDeviceAsync(
context,
"Sensor",
"urn:acme:sensor:4711").ConfigureAwait(false);
await device.RegisterAsAssetAsync(
context.GetRequiredService<IAssetManagement>(),
asset => asset
.WithLocation(AssetLocationKind.Hierarchical, "Plant1/Hall3", writable: true)
.WithLocalTime(60, writable: true),
context.CancellationToken).ConfigureAwait(false);
}));
}
/// <summary>
/// Builds a part of a machine that is an asset of its own: an object
/// below the machine with its own <c>ProductInstanceUri</c>.
/// </summary>
private static INodeBuilder<BaseObjectState> CreatePart(
IAssetManagementSetupContext context,
BaseObjectState? machine,
string name,
string productInstanceUri)
{
ushort di = (ushort)context.Manager.Server.NamespaceUris.GetIndex(Opc.Ua.Di.Namespaces.OpcUaDi);
if (machine == null)
{
INodeBuilder<BaseObjectState> standalone = context.Builder.AddObject(
new QualifiedName(name, context.Manager.InstanceNamespaceIndex),
Ua.ObjectIds.ObjectsFolder);
PropertyState standaloneUri = standalone.Node.AddProperty<string, VariantBuilder>(
"ProductInstanceUri",
Ua.DataTypeIds.String,
ValueRanks.Scalar);
standaloneUri.BrowseName = new QualifiedName("ProductInstanceUri", di);
standaloneUri.NodeId = context.Manager.New(context.Manager.SystemContext, standaloneUri);
standaloneUri.WrappedValue = Variant.From(productInstanceUri);
context.Manager.AddNode(standaloneUri);
return standalone;
}
var part = new BaseObjectState(machine)
{
BrowseName = new QualifiedName(name, context.Manager.InstanceNamespaceIndex),
DisplayName = new LocalizedText(name),
TypeDefinitionId = Ua.ObjectTypeIds.BaseObjectType,
ReferenceTypeId = Ua.ReferenceTypeIds.HasComponent
};
part.NodeId = context.Manager.New(context.Manager.SystemContext, part);
machine.AddChild(part);
PropertyState uri = part.AddProperty<string, VariantBuilder>(
"ProductInstanceUri",
Ua.DataTypeIds.String,
ValueRanks.Scalar);
uri.BrowseName = new QualifiedName("ProductInstanceUri", di);
uri.NodeId = context.Manager.New(context.Manager.SystemContext, uri);
uri.WrappedValue = Variant.From(productInstanceUri);
context.Manager.AddNode(part);
return context.Builder.Node<BaseObjectState>(part.NodeId);
}
/// <summary>
/// Adds the <c>2:OperationCounters</c> group with one counter, nested
/// one group deep as §10.3 allows.
/// </summary>
private static void AddOperationCounter(IAssetManagementSetupContext context, BaseObjectState machine)
{
ushort di = (ushort)context.Manager.Server.NamespaceUris.GetIndex(Opc.Ua.Di.Namespaces.OpcUaDi);
var counters = new BaseObjectState(machine)
{
BrowseName = new QualifiedName("OperationCounters", di),
DisplayName = new LocalizedText("OperationCounters"),
TypeDefinitionId = FunctionalGroup(context),
ReferenceTypeId = Ua.ReferenceTypeIds.HasComponent
};
counters.NodeId = context.Manager.New(context.Manager.SystemContext, counters);
machine.AddChild(counters);
var group = new BaseObjectState(counters)
{
BrowseName = new QualifiedName("Spindle", context.Manager.InstanceNamespaceIndex),
DisplayName = new LocalizedText("Spindle"),
TypeDefinitionId = FunctionalGroup(context),
ReferenceTypeId = Ua.ReferenceTypeIds.HasComponent
};
group.NodeId = context.Manager.New(context.Manager.SystemContext, group);
counters.AddChild(group);
PropertyState hours = group.AddProperty<double, VariantBuilder>(
"OperationDuration",
Ua.DataTypeIds.Duration,
ValueRanks.Scalar);
hours.BrowseName = new QualifiedName("OperationDuration", di);
hours.NodeId = context.Manager.New(context.Manager.SystemContext, hours);
hours.WrappedValue = Variant.From(3_600_000d);
context.Manager.AddNode(counters);
}
private static NodeId FunctionalGroup(IAssetManagementSetupContext context)
{
return ExpandedNodeId.ToNodeId(
Opc.Ua.Di.ObjectTypeIds.FunctionalGroupType,
context.Manager.Server.NamespaceUris);
}
private static TimeZoneDataType? TimeZoneOf(DataValue value)
{
TimeZoneDataType zone;
return value.WrappedValue.TryGetStructure(out zone!) ? zone : null;
}
}
}