mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-21 09:06:37 +08:00
15f9a5ebcc
# Description `MachineryClient` browses the `Machines` folder, the `Components` add-in, the `MachineryBuildingBlocks` organizer, the energy resources and the process values with `HierarchicalReferences` and subtypes, and turned every returned `ReferenceDescription` into a `MachineEntry`. Browse returns one description per reference, not per node, and `HasEventSource` and its subtype `HasNotifier` are hierarchical references. A machine that the `Machines` folder organizes and that is also registered as a notifier of the folder - how a server exposes its event hierarchy below the `Server` object once alarms are attached - was therefore returned twice by `EnumerateMachinesAsync` and `DiscoverMachinesAsync`. The same held for a component that is an event source of its `Components` folder and for a process value that is an event source of `Monitoring`. The fix: - The shared browse helper reports each target NodeId once and keeps the first description. Its `BrowseName`, `DisplayName` and `TypeDefinition` belong to the node and are the same for every reference that leads to it. - All hierarchical references are still followed. Restricting the browse to `Organizes` would lose machines, components and process values a server references with another hierarchical reference type such as `HasComponent`, so an address space without duplicate references returns exactly what it returned before. - `EnumerateProcessValuesAsync` looks below the machinery item and below its `Monitoring`; a process value reachable from both is now reported once as well. The public API does not change. ## Changes - `src/Opc.Ua.Machinery.Client/MachineryClient.cs`: `BrowseChildrenAsync` skips a NodeId it has already returned; the remarks of `EnumerateMachinesAsync` say so. - `src/Opc.Ua.Machinery.Client/MachineryClient.ProcessValues.cs`: `EnumerateProcessValuesAsync` skips a process value below `Monitoring` it has already returned below the item. Every enumeration of the client goes through `BrowseChildrenAsync`: `EnumerateMachinesAsync`, `DiscoverMachinesAsync`, `EnumerateComponentsAsync`, `EnumerateBuildingBlocksAsync`, `EnumerateEnergyResourcesAsync`, `EnumerateMeteringPointsAsync`, `EnumerateSubMetersAsync`, `EnumerateProcessValuesAsync`, and the child walks of `ReadLifetimeCountersAsync`, `EnumerateEquipmentAsync`, `ReadMeteringPointAsync` and `ReadPublishedResultsAsync`. ## Tests - **New, end-to-end** (`MachineryEndToEndTests.NodesThatAreAlsoEventSourcesOfTheirParentAreEnumeratedOnceAsync`): the test press links the machine to `Machines` with `HasNotifier`, the `HydraulicUnit` component to `Components` and the oil-temperature process value to `Monitoring` with `HasEventSource`, each in addition to its organizing reference, and expects each node once from `EnumerateMachinesAsync`, `DiscoverMachinesAsync`, `EnumerateComponentsAsync` and `EnumerateProcessValuesAsync` over `opc.tcp`. - **New, unit** (`MachineryClientTests.ANodeReachedThroughTwoReferencesIsEnumeratedOnceAsync`): a browse result that carries the same machine under `Organizes` and `HasNotifier`. - **Fail without the fix:** with `src/Opc.Ua.Machinery.Client` from master, all four assertions of the end-to-end test fail - two machines, two NodeIds, two components and two process values instead of one each. - `Opc.Ua.Machinery.Tests` passed 167/167 on net10.0 and 167/167 on net8.0 (macOS). - `Opc.Ua.Machinery.Client` builds for net48, net8.0, net9.0 and net10.0 with 0 warnings. - `dotnet format` (whitespace, style, analyzers) on the changed files: nothing on the changed lines (the `ENDOFLINE` findings concern the whole of every file in a checkout with LF line endings). - Changed lines covered: 8/8 (100 %). - Fork CI (full matrix incl. macOS) and CodeQL: [CI run 37201766371](https://github.com/biancode/UA-.NETStandard/actions/runs/37201766371) and [CodeQL run 37201768280](https://github.com/biancode/UA-.NETStandard/actions/runs/37201768280), both green. ## Notes for review - No extra request: the de-duplication happens on the result of the browse the client already made. - Of the sibling companion clients, `PumpsClient.EnumeratePumpsAsync` and `ScalesClient.EnumerateScalesAsync` already de-duplicate across their two roots. `EnumeratePumpsUnderAsync`, `EnumerateScalesUnderAsync`, `EnumerateSystemScalesAsync` and the DI device discovery follow the same browse pattern without de-duplication; they are not changed here. ## Related Issues - Fixes #4670 ## 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. (Affected 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>
314 lines
13 KiB
C#
314 lines
13 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.Collections.Generic;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using MachineryBrowseNames = Opc.Ua.Machinery.BrowseNames;
|
|
using PadimBrowseNames = Opc.Ua.PADIM.BrowseNames;
|
|
using ProcessValueBrowseNames = Opc.Ua.Machinery.ProcessValues.BrowseNames;
|
|
|
|
namespace Opc.Ua.Machinery.Client
|
|
{
|
|
public sealed partial class MachineryClient
|
|
{
|
|
/// <summary>
|
|
/// Enumerates the OPC 40001-2 process values a machinery item
|
|
/// publishes.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// OPC 40001-2 does not fix where process values hang — the examples
|
|
/// put them on a sensor component, on the machine, and below
|
|
/// <c>Monitoring</c> — so they are found by type definition rather
|
|
/// than by browse path: every object directly below the item, or
|
|
/// directly below its <c>Monitoring</c> object, whose type is
|
|
/// <c>ProcessValueType</c> or a subtype counts. The process values of
|
|
/// a component are found by passing the component.
|
|
/// </remarks>
|
|
/// <param name="machineryItem">The machine or component to inspect.</param>
|
|
/// <param name="cancellationToken">Cancels the operation.</param>
|
|
public async IAsyncEnumerable<MachineEntry> EnumerateProcessValuesAsync(
|
|
NodeId machineryItem,
|
|
[EnumeratorCancellation] CancellationToken cancellationToken = default)
|
|
{
|
|
if (!TryGetNamespaceIndex(
|
|
Opc.Ua.Machinery.ProcessValues.Namespaces.MachineryProcessValues,
|
|
out ushort namespaceIndex))
|
|
{
|
|
yield break;
|
|
}
|
|
var processValueTypeId = new NodeId(
|
|
Opc.Ua.Machinery.ProcessValues.ObjectTypes.ProcessValueType,
|
|
namespaceIndex);
|
|
|
|
// A process value below the item may also be organized by or be
|
|
// an event source of its Monitoring, so it is reported once.
|
|
var seen = new HashSet<NodeId>();
|
|
await foreach (MachineEntry entry in EnumerateProcessValuesBelowAsync(
|
|
machineryItem,
|
|
processValueTypeId,
|
|
cancellationToken).ConfigureAwait(false))
|
|
{
|
|
seen.Add(entry.NodeId);
|
|
yield return entry;
|
|
}
|
|
|
|
if (!TryGetNamespaceIndex(
|
|
Opc.Ua.Machinery.Namespaces.Machinery,
|
|
out ushort machineryNamespaceIndex))
|
|
{
|
|
yield break;
|
|
}
|
|
NodeId monitoring = await ResolveChildAsync(
|
|
machineryItem,
|
|
new QualifiedName(MachineryBrowseNames.Monitoring, machineryNamespaceIndex),
|
|
cancellationToken).ConfigureAwait(false);
|
|
if (monitoring.IsNull)
|
|
{
|
|
yield break;
|
|
}
|
|
await foreach (MachineEntry entry in EnumerateProcessValuesBelowAsync(
|
|
monitoring,
|
|
processValueTypeId,
|
|
cancellationToken).ConfigureAwait(false))
|
|
{
|
|
if (seen.Add(entry.NodeId))
|
|
{
|
|
yield return entry;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reads one OPC 40001-2 process value with its metadata, limits,
|
|
/// setpoint and status.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Everything but the signal itself is optional in the part, so a
|
|
/// property the server does not publish comes back as
|
|
/// <see langword="null"/> rather than as an error.
|
|
/// </remarks>
|
|
/// <param name="processValue">The process value to read.</param>
|
|
/// <param name="cancellationToken">Cancels the operation.</param>
|
|
public async ValueTask<MachineryProcessValue?> ReadProcessValueAsync(
|
|
NodeId processValue,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
if (processValue.IsNull)
|
|
{
|
|
return null;
|
|
}
|
|
ushort padimNamespaceIndex = NamespaceIndexOf(Opc.Ua.PADIM.Namespaces.PADIM);
|
|
ushort processValueNamespaceIndex = NamespaceIndexOf(
|
|
Opc.Ua.Machinery.ProcessValues.Namespaces.MachineryProcessValues);
|
|
|
|
var signalName = new QualifiedName(
|
|
PadimBrowseNames.AnalogSignal,
|
|
padimNamespaceIndex);
|
|
NodeId signal = await ResolveChildAsync(processValue, signalName, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
if (signal.IsNull)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var setpointName = new QualifiedName(
|
|
ProcessValueBrowseNames.ProcessValueSetpoint,
|
|
processValueNamespaceIndex);
|
|
var statusName = new QualifiedName(
|
|
ProcessValueBrowseNames.Status,
|
|
processValueNamespaceIndex);
|
|
var suppressionName = new QualifiedName(
|
|
ProcessValueBrowseNames.AlarmSuppression,
|
|
processValueNamespaceIndex);
|
|
|
|
Dictionary<QualifiedName, Variant> objectValues = await ReadChildValuesAsync(
|
|
processValue,
|
|
[signalName, setpointName, statusName, suppressionName],
|
|
Opc.Ua.ReferenceTypeIds.HierarchicalReferences,
|
|
cancellationToken).ConfigureAwait(false);
|
|
|
|
var lowLowName = new QualifiedName(
|
|
ProcessValueBrowseNames.LowLowLimit,
|
|
processValueNamespaceIndex);
|
|
var lowName = new QualifiedName(
|
|
ProcessValueBrowseNames.LowLimit,
|
|
processValueNamespaceIndex);
|
|
var highName = new QualifiedName(
|
|
ProcessValueBrowseNames.HighLimit,
|
|
processValueNamespaceIndex);
|
|
var highHighName = new QualifiedName(
|
|
ProcessValueBrowseNames.HighHighLimit,
|
|
processValueNamespaceIndex);
|
|
var percentageName = new QualifiedName(
|
|
ProcessValueBrowseNames.PercentageValue,
|
|
processValueNamespaceIndex);
|
|
var unitsName = new QualifiedName(Opc.Ua.BrowseNames.EngineeringUnits);
|
|
var rangeName = new QualifiedName(Opc.Ua.BrowseNames.EURange);
|
|
|
|
Dictionary<QualifiedName, Variant> signalValues = await ReadChildValuesAsync(
|
|
signal,
|
|
[
|
|
lowLowName,
|
|
lowName,
|
|
highName,
|
|
highHighName,
|
|
percentageName,
|
|
unitsName,
|
|
rangeName
|
|
],
|
|
Opc.Ua.ReferenceTypeIds.HierarchicalReferences,
|
|
cancellationToken).ConfigureAwait(false);
|
|
|
|
return new MachineryProcessValue
|
|
{
|
|
NodeId = processValue,
|
|
SignalNodeId = signal,
|
|
Value = AsDouble(objectValues, signalName),
|
|
Setpoint = AsDouble(objectValues, setpointName),
|
|
Status = AsUInt16(objectValues, statusName),
|
|
AlarmSuppression = AsUInt16(objectValues, suppressionName),
|
|
LowLowLimit = AsDouble(signalValues, lowLowName),
|
|
LowLimit = AsDouble(signalValues, lowName),
|
|
HighLimit = AsDouble(signalValues, highName),
|
|
HighHighLimit = AsDouble(signalValues, highHighName),
|
|
PercentageValue = AsDouble(signalValues, percentageName),
|
|
EngineeringUnits = AsEngineeringUnits(signalValues, unitsName),
|
|
EuRange = AsRange(signalValues, rangeName)
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Calls the OPC 40001-2 <c>ZeroPointAdjustment</c> method of a
|
|
/// process value.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// A conformant server reports a <c>ZeroPointAdjustmentEventType</c>
|
|
/// event for every call; subscribe to the process value to see it.
|
|
/// </remarks>
|
|
/// <param name="processValue">The process value to adjust.</param>
|
|
/// <param name="cancellationToken">Cancels the operation.</param>
|
|
/// <returns>The service result of the call.</returns>
|
|
/// <exception cref="ServiceResultException">
|
|
/// The process value publishes no <c>ZeroPointAdjustment</c> method.
|
|
/// </exception>
|
|
public async ValueTask<StatusCode> ZeroPointAdjustmentAsync(
|
|
NodeId processValue,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
ushort padimNamespaceIndex = NamespaceIndexOf(Opc.Ua.PADIM.Namespaces.PADIM);
|
|
NodeId method = await ResolveChildAsync(
|
|
processValue,
|
|
new QualifiedName(
|
|
PadimBrowseNames.ZeroPointAdjustment,
|
|
padimNamespaceIndex),
|
|
cancellationToken).ConfigureAwait(false);
|
|
if (method.IsNull)
|
|
{
|
|
throw ServiceResultException.Create(
|
|
StatusCodes.BadNotFound,
|
|
"The process value publishes no ZeroPointAdjustment method.");
|
|
}
|
|
|
|
CallResponse response = await Session.CallAsync(
|
|
requestHeader: null,
|
|
methodsToCall: new[]
|
|
{
|
|
new CallMethodRequest
|
|
{
|
|
ObjectId = processValue,
|
|
MethodId = method,
|
|
InputArguments = []
|
|
}
|
|
}.ToArrayOf(),
|
|
ct: cancellationToken).ConfigureAwait(false);
|
|
|
|
return response.Results.Count == 0
|
|
? StatusCodes.BadUnexpectedError
|
|
: response.Results[0].StatusCode;
|
|
}
|
|
|
|
private async IAsyncEnumerable<MachineEntry> EnumerateProcessValuesBelowAsync(
|
|
NodeId parent,
|
|
NodeId processValueTypeId,
|
|
[EnumeratorCancellation] CancellationToken cancellationToken)
|
|
{
|
|
await foreach (MachineEntry entry in EnumerateChildObjectsAsync(
|
|
parent,
|
|
cancellationToken).ConfigureAwait(false))
|
|
{
|
|
// A vendor subtype of ProcessValueType is a process value too.
|
|
if (await Session.NodeCache
|
|
.IsTypeOfAsync(entry.TypeDefinitionId, processValueTypeId, cancellationToken)
|
|
.ConfigureAwait(false))
|
|
{
|
|
yield return entry;
|
|
}
|
|
}
|
|
}
|
|
|
|
private static ushort? AsUInt16(
|
|
Dictionary<QualifiedName, Variant> values,
|
|
QualifiedName name)
|
|
{
|
|
return values.TryGetValue(name, out Variant value) &&
|
|
value.TryGetValue(out ushort number)
|
|
? number
|
|
: null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Decodes a structure read from the wire. The context-taking overload
|
|
/// is the one that works for a value that arrived as a binary
|
|
/// <see cref="ExtensionObject"/>, which is what a server sends unless
|
|
/// the session already knows the type.
|
|
/// </summary>
|
|
private EUInformation? AsEngineeringUnits(
|
|
Dictionary<QualifiedName, Variant> values,
|
|
QualifiedName name)
|
|
{
|
|
return values.TryGetValue(name, out Variant value) &&
|
|
value.TryGetStructure<EUInformation>(Session.MessageContext, out EUInformation? units)
|
|
? units
|
|
: null;
|
|
}
|
|
|
|
private Opc.Ua.Range? AsRange(
|
|
Dictionary<QualifiedName, Variant> values,
|
|
QualifiedName name)
|
|
{
|
|
return values.TryGetValue(name, out Variant value) &&
|
|
value.TryGetStructure<Opc.Ua.Range>(Session.MessageContext, out Opc.Ua.Range? range)
|
|
? range
|
|
: null;
|
|
}
|
|
}
|
|
}
|