mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-18 14:43:08 +08:00
668310f21f
# Description The fluent node-manager pipeline had two synchronous chokepoints, and two independent efforts have now hit both of them. `Configure` is a `partial void`, so it cannot `await`. A manager whose wiring depends on asynchronous setup had to invent a second hook outside the pipeline, create its own builder there, and hand-roll `CreateFluentBuilder(...).Configure(...).Seal()` inside it. `Seal()` was synchronous, so nothing a registration staged during `Configure` could be completed by awaiting. Registrations that needed to await either blocked — `EventSourceRegistry` did `.GetAwaiter().GetResult()` on the manager's root-notifier registration — or could not be expressed at all. ## What changed **`FluentNodeManagerBase.ConfigureAsync(INodeManagerBuilder, CancellationToken)`** is the awaitable wiring seam. It runs once per activation, with the manager's attached builder, immediately *before* the synchronous `Configure` partial(s) — so instances it materialises are in the address space by the time `Configure` wires callbacks against them. The default implementation is a no-op. It is a `virtual` method rather than a second `partial` declaration because a partial method can be optional (`partial void`, no return value) or awaitable (an extended partial method, which must be implemented) — not both, and the generator would otherwise have to detect which one the user declared. `partial void Configure(INodeManagerBuilder)` keeps working unchanged; a manager uses either hook or both. **`NodeManagerBuilder.Seal()` becomes `SealAsync(CancellationToken)`.** Sealing is now the single point where registrations that could not finish inside `Configure` get their turn to await. Every seal site awaits it, so a later change can move registry *setup* onto the same seam. **`DiNodeManager` now runs the standard pipeline itself** — create and attach the builder, `await ConfigureAsync`, `RegisterAuthoredNodesAsync`, `CompleteConfigureAsync`, the post-setup runner, then `await builder.SealAsync` — instead of handing subclasses a bare callback and leaving them to build and seal on their own. DI subclasses gain node registration and the reverse-reference pass, which they previously skipped. Sealing deliberately comes **after** the post-setup runner. The fluent registries are owned by the manager, not by a single builder, and sealing starts them — so sealing first locks post-setup configurators out of registering simulation loops of their own, which is exactly what `AddRobotics`' configurators do. Sealing before the runner makes `MinimalRobotServer` fail to start with *"Cannot add a simulation loop after the registry has started"*. Worth knowing for follow-up work: with several builders attached to one manager, the first seal freezes the shared registry for all of them. ## Workarounds removed - **`DiNodeManager.OnAddressSpaceReadyAsync`** — deleted. Its three overriders (`RoboticsNodeManager`, and the `PumpNodeManager` / `GeneratorNodeManager` samples) now override `ConfigureAsync` and no longer hand-roll `CreateFluentBuilder(...).Configure(Configure).Seal()`. - **`EventSourceRegistry`'s `.GetAwaiter().GetResult()`** on `AddRootNotifierAsync` — gone. `Publish(..., RegisterAsRootNotifier: true)` now stages the registration and `SealAsync` drains it, so the wait happens on an awaited path. A source whose root-notifier registration fails is rolled out of the registry before the failure surfaces, and a registry disposed before its builder sealed drops what it staged. - **`Isa95NodeManager.ConfigureStatusEvents()`** — the synchronous second builder pass is now `ConfigureStatusEventsAsync(CancellationToken)`, awaited from `CreateAddressSpaceAsync`. (`ConfigureCatalogChanges()` stays synchronous: it starts a background task and never seals a builder, so there was nothing to convert.) - **`IRoboticsBuildContext.Seal()`** — now `SealAsync(CancellationToken)`. These really were `NodeManagerBuilder.Seal()` calls behind a same-named method. The state transition still happens under the context lock; the builder's asynchronous completion runs outside it, so no `await` is taken while the lock is held. - The Pump / Generator incremental registration callbacks (`onRegistered`) changed from `Action<T>` to `Func<T, CancellationToken, ValueTask>` so their per-instance builder pass can await its own seal. No sync-over-async was introduced anywhere. `Dispose(bool)` is unchanged and stays non-blocking; teardown remains in `DeleteAddressSpaceAsync`. `NodeManagerBuilder.Seal()` and `IRoboticsBuildContext.Seal()` are removed rather than kept as synchronous overloads. A synchronous seal that silently skipped the asynchronous completion would reintroduce exactly the failure mode this change exists to remove. ## Generator `NodeManagerTemplates` emits, in order: predefined nodes load → `await ConfigureAsync(__m_builder, cancellationToken)` → `Configure(__m_builder)` and the typed `Configure` → `RegisterAuthoredNodesAsync` → `CompleteConfigureAsync` → `await SealConfigurationAsync(__m_builder, cancellationToken)`. `NodeManagerGeneratorTests` asserts that order literally, and that neither `__m_builder.Seal()` nor the synchronous `SealConfiguration(__m_builder)` is emitted. ### Merging with #4432 #4432 landed on `master` while this was in review and reworked the same seam from the other side: it split `Seal()` into `SealGraphAuthoring()` + `StartSimulations()` so a manager can replay `NotifyNodeAdded` *between* the two halves — sealing first stops a lifecycle handler authoring nodes nothing would register, starting the simulations last stops a simulated value change preceding its own node''s `OnNodeAdded` — and added `FluentNodeManagerBase.SealConfiguration(builder)` as the one call the generator emits. Both intents are kept. That split is precisely why the asynchronous completion could not simply live inside `SealAsync`: a manager reaching the seam through the split path would silently skip it, which is the failure mode this PR exists to remove. So the asynchronous half became its own step: - `NodeManagerBuilder.CompleteSealAsync(ct)` drains the staged root-notifier registrations, then starts the simulations. `SealAsync(ct)` is `SealGraphAuthoring()` followed by it. - #4432''s synchronous `StartSimulations()` is gone, folded into `CompleteSealAsync`. It had exactly one production caller after the merge, and leaving it standing would have kept a second, synchronous way to activate a builder that skips the staged registrations — the very hazard this PR removes. Activation is now one step with one entry point; the *split* itself stays, because the replay has to sit between the halves. - `SealConfiguration` becomes `SealConfigurationAsync(builder, ct)`: seal the graph, replay `NotifyNodeAdded`, then `CompleteSealAsync`. Activation still happens last, so #4432''s ordering guarantee holds unchanged. ## Consumers unblocked - **#4434 ("Reimplement the GDS ApplicationsNodeManager as a generated fluent node manager")** adds `OnAddressSpaceReadyAsync` to `FluentNodeManagerBase` purely because, in its own words, *"`Configure` is a `partial void` and cannot await"*. That hook is unnecessary once `ConfigureAsync` exists — the GDS manager overrides `ConfigureAsync` instead, and the ordering it wants (predefined nodes → async setup → `Configure`) is what the generator now emits. #4434 has not merged yet, so it can drop its addition rather than have it simplified afterwards. - **Branch `romanett/fluent-node-behaviors`** moved `SimulationRegistry`, `EventSourceRegistry`, `MonitoredSourceRegistry` and the alarm wiring onto `AttachToType`/`Attach` for *release* only, because activation ran from `CompleteConfigureAsync` and most managers only called the synchronous `Seal()`. Every seal site now reaches `SealAsync`, so registry and alarm *setup* can move onto behavior activation too — the remaining half of that work. ## Tests - New `DiNodeManagerConfigureAsyncTests` drives the real `DiNodeManager.CreateAddressSpaceAsync` and asserts the hook runs once with an attached builder, that nodes it stages are registered, that their references to externally owned nodes are published, and that the builder is sealed before `CreateAddressSpaceAsync` returns. - `PublishTests` now pins the root-notifier deferral contract: registration is staged during `Configure`, lands only on the seal, and draining twice does not double-register. - Every `Seal()` call site in the test suites became `await ...SealAsync()`, including the three #4432 added in `NodeSetImportBuilderTests` and `SimulationBuilderExtensionsTests`. ## Related Issues No tracking issue was opened for this; it is the shared prerequisite extracted from #4434 and branch `romanett/fluent-node-behaviors`, both of which had independently worked around the same synchrony. Happy to open one if maintainers want the ADR trail. ## 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. - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. - [ ] I have addressed **all** PR feedback received. ### What was actually run locally `UA.slnx` builds clean. Post-merge on **net10.0**: `Opc.Ua.Server.Tests` 5020/0 and `Opc.Ua.SourceGeneration.Core.Tests` 3813/0. Pre-merge the same run plus `Opc.Ua.Di.Tests` 425/0, `Opc.Ua.Robotics.Tests` 627/0, `Opc.Ua.ISA95.Tests` 136/0, `Opc.Ua.Positioning.Tests` and `Opc.Ua.Robotics.Intent.Tests` were all green; `MinimalRobotServer` was also started directly to confirm the hosted robotics path comes up. Three caveats, so the unchecked box above is not a mystery: the full suite was **not** run against .NET Framework locally; `Opc.Ua.OpenUsd.Tests` has one pre-existing failure on this machine (`StructuredCartesianCoordinatesAreAccepted` expects `"1.5"` and gets `"1,5"` — a German-locale decimal separator, unrelated to this change); and one pre-existing `CA1861` warning comes from `NodeSetImportIntegrationTests.cs`, which is byte-identical to `master` on this branch. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
745 lines
33 KiB
C#
745 lines
33 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2025 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.Concurrent;
|
|
using System.Globalization;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Pumps;
|
|
using Opc.Ua.Server.Fluent;
|
|
using Opc.Ua.Server.Historian;
|
|
|
|
namespace Pumps
|
|
{
|
|
/// <summary>
|
|
/// Sibling partial that wires per-node callbacks for the
|
|
/// <see cref="PumpNodeManager"/> using the fluent builder.
|
|
/// Demonstrates the OPC 40223 Pumps companion specification
|
|
/// with a full simulation loop.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The node manager is hand-written and uses the fluent
|
|
/// <see cref="INodeManagerBuilder"/> API to wire per-node
|
|
/// callbacks. See <see cref="Configure"/> for the entry point.
|
|
/// </remarks>
|
|
public partial class PumpNodeManager
|
|
{
|
|
partial void Configure(INodeManagerBuilder builder)
|
|
{
|
|
Server.Telemetry.CreateLogger<PumpNodeManager>()
|
|
.ConfiguringPumpNodeManagerFluentWiring();
|
|
|
|
builder.UseHistorian()
|
|
.UseInMemoryProvider()
|
|
.RegisterAsDefault();
|
|
|
|
foreach (PumpState pump in m_pumpStates)
|
|
{
|
|
RegisterPumpSimulation(builder, pump);
|
|
}
|
|
|
|
builder.Simulation(SimulationInterval)
|
|
.OnTick((ctx, elapsed) => AdvanceSimulation());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Wires a pump created after the initial fluent configuration into
|
|
/// the already-running manager simulation.
|
|
/// </summary>
|
|
/// <param name="pump">The registered pump instance.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
private ValueTask RegisterPumpSimulationAsync(
|
|
PumpState pump,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
ushort pumpsNs = (ushort)Server.NamespaceUris.GetIndex(
|
|
Opc.Ua.Pumps.Namespaces.Pumps);
|
|
NodeManagerBuilder builder = CreateFluentBuilder(pumpsNs);
|
|
RegisterPumpSimulation(builder, pump);
|
|
return builder.SealAsync(cancellationToken);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Configures the variable updaters, alarms, and phase profile for one
|
|
/// pump instance.
|
|
/// </summary>
|
|
/// <param name="builder">The active fluent builder.</param>
|
|
/// <param name="pump">The pump to configure.</param>
|
|
/// <exception cref="ServiceResultException"></exception>
|
|
private void RegisterPumpSimulation(
|
|
INodeManagerBuilder builder,
|
|
PumpState pump)
|
|
{
|
|
lock (m_simulationRegistrationLock)
|
|
{
|
|
if (m_pumpSimulations.ContainsKey(pump.NodeId))
|
|
{
|
|
throw ServiceResultException.Create(
|
|
StatusCodes.BadConfigurationError,
|
|
"Pump '{0}' (id '{1}') already has a simulation registered.",
|
|
pump.BrowseName,
|
|
pump.NodeId);
|
|
}
|
|
|
|
int profileIndex = m_nextSimulationProfile++;
|
|
WithIdentification(builder, pump, profileIndex + 1);
|
|
WithMaintenance(builder, pump);
|
|
PumpSimulationState simulation = CreatePumpSimulation(
|
|
builder,
|
|
pump,
|
|
profileIndex);
|
|
simulation.Initialize(Volatile.Read(ref m_simulationTicks));
|
|
if (!m_pumpSimulations.TryAdd(pump.NodeId, simulation))
|
|
{
|
|
throw ServiceResultException.Create(
|
|
StatusCodes.BadConfigurationError,
|
|
"Pump '{0}' (id '{1}') already has a simulation registered.",
|
|
pump.BrowseName,
|
|
pump.NodeId);
|
|
}
|
|
|
|
// The OpenUSD twin of this pump renders this simulation.
|
|
if (m_twins.TryGetValue(pump.NodeId, out PumpTwin? twin))
|
|
{
|
|
twin.Simulation = simulation;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Configures the nameplate of one simulated unit with the
|
|
/// identification data published in <c>DATASHEET.md</c>. The
|
|
/// properties themselves are materialised by
|
|
/// <see cref="MaterialiseNameplate"/>; this method
|
|
/// only assigns their values through the fluent builder. Fields
|
|
/// that identify the individual unit rather than the product are
|
|
/// derived from <paramref name="pumpNumber"/>.
|
|
/// </summary>
|
|
/// <param name="builder">The active fluent builder.</param>
|
|
/// <param name="pump">The pump whose nameplate is configured.</param>
|
|
/// <param name="pumpNumber">One-based number of the simulated unit.</param>
|
|
private static void WithIdentification(
|
|
INodeManagerBuilder builder,
|
|
PumpState pump,
|
|
int pumpNumber)
|
|
{
|
|
string serialNumber = "SN-" + pumpNumber.ToString("D3", CultureInfo.InvariantCulture);
|
|
string assetId = "PMP-" +
|
|
(1000 + pumpNumber).ToString(CultureInfo.InvariantCulture);
|
|
string componentName = "Feed Pump " + (char)('A' + ((pumpNumber - 1) % 26));
|
|
string location = "Plant 1 / Utility Skid / Bay " +
|
|
(pumpNumber + 2).ToString(CultureInfo.InvariantCulture);
|
|
string fabricationNumber = "F-2025-" +
|
|
pumpNumber.ToString("D4", CultureInfo.InvariantCulture);
|
|
|
|
builder.Node(pump.Identification!.NodeId)
|
|
.WithProperty(
|
|
"Manufacturer",
|
|
new LocalizedText(PumpDatasheet.Nameplate.Manufacturer))
|
|
.WithProperty(
|
|
"ManufacturerUri",
|
|
PumpDatasheet.Nameplate.ManufacturerUri)
|
|
.WithProperty(
|
|
"Model",
|
|
new LocalizedText(PumpDatasheet.Nameplate.Model))
|
|
.WithProperty("ProductCode", PumpDatasheet.Nameplate.ProductCode)
|
|
.WithProperty("DeviceClass", PumpDatasheet.Nameplate.DeviceClass)
|
|
.WithProperty(
|
|
"HardwareRevision",
|
|
PumpDatasheet.Nameplate.HardwareRevision)
|
|
.WithProperty(
|
|
"SoftwareRevision",
|
|
PumpDatasheet.Nameplate.SoftwareRevision)
|
|
.WithProperty("SerialNumber", serialNumber)
|
|
.WithProperty(
|
|
"ProductInstanceUri",
|
|
PumpDatasheet.Nameplate.ProductInstanceUriPrefix + serialNumber)
|
|
.WithProperty("AssetId", assetId)
|
|
.WithProperty("ComponentName", new LocalizedText(componentName))
|
|
.WithProperty("Location", location)
|
|
.WithProperty(
|
|
"YearOfConstruction",
|
|
PumpDatasheet.Nameplate.YearOfConstruction)
|
|
.WithProperty(
|
|
"MonthOfConstruction",
|
|
PumpDatasheet.Nameplate.MonthOfConstruction)
|
|
.WithProperty(
|
|
"DayOfConstruction",
|
|
PumpDatasheet.Nameplate.DayOfConstruction)
|
|
.WithProperty(
|
|
"ArticleNumber",
|
|
PumpDatasheet.Nameplate.ArticleNumber)
|
|
.WithProperty(
|
|
"OrderProductCode",
|
|
PumpDatasheet.Nameplate.OrderProductCode)
|
|
.WithProperty(
|
|
"TypeOfProduct",
|
|
PumpDatasheet.Nameplate.TypeOfProduct)
|
|
.WithProperty("Supplier", PumpDatasheet.Nameplate.Supplier)
|
|
.WithProperty(
|
|
"CountryOfOrigin",
|
|
PumpDatasheet.Nameplate.CountryOfOrigin)
|
|
.WithProperty("FabricationNumber", fabricationNumber);
|
|
}
|
|
|
|
private void WithMaintenance(INodeManagerBuilder builder, PumpState pump)
|
|
{
|
|
var functionalGroupType = NodeId.Create(
|
|
Opc.Ua.Di.ObjectTypes.FunctionalGroupType,
|
|
Opc.Ua.Di.Namespaces.OpcUaDi,
|
|
Server.NamespaceUris);
|
|
var generalMaintenance = new QualifiedName(
|
|
"GeneralMaintenance",
|
|
(ushort)Server.NamespaceUris.GetIndex(Opc.Ua.Pumps.Namespaces.Pumps));
|
|
|
|
builder.Node(pump.Maintenance!.NodeId)
|
|
.AddObject(generalMaintenance, functionalGroupType)
|
|
.WithProperty(
|
|
"MaintenancePlan",
|
|
Variant.From("Inspect seals and bearings every 30 days."));
|
|
}
|
|
|
|
private PumpSimulationState CreatePumpSimulation(
|
|
INodeManagerBuilder builder,
|
|
PumpState pump,
|
|
int profileIndex)
|
|
{
|
|
MeasurementsState measurements = pump.Operational!.Measurements!;
|
|
|
|
AddMeasurement(
|
|
builder,
|
|
measurements.DifferentialPressure!.NodeId,
|
|
EngineeringUnits.Pascal,
|
|
min: PumpDatasheet.Ranges.DifferentialPressureMin,
|
|
max: PumpDatasheet.Ranges.DifferentialPressureMax,
|
|
out IValueUpdater<double> pressure);
|
|
AddMeasurement(
|
|
builder,
|
|
measurements.FluidTemperature!.NodeId,
|
|
EngineeringUnits.Kelvin,
|
|
min: PumpDatasheet.Ranges.FluidTemperatureMin,
|
|
max: PumpDatasheet.Ranges.FluidTemperatureMax,
|
|
out IValueUpdater<double> fluidTemperature);
|
|
AddMeasurement(
|
|
builder,
|
|
measurements.BearingTemperature!.NodeId,
|
|
EngineeringUnits.Kelvin,
|
|
min: PumpDatasheet.Ranges.BearingTemperatureMin,
|
|
max: PumpDatasheet.Ranges.BearingTemperatureMax,
|
|
out IValueUpdater<double> bearingTemperature);
|
|
AddMeasurement(
|
|
builder,
|
|
measurements.PumpPowerInput!.NodeId,
|
|
EngineeringUnits.Watt,
|
|
min: PumpDatasheet.Ranges.PumpPowerInputMin,
|
|
max: PumpDatasheet.Ranges.PumpPowerInputMax,
|
|
out IValueUpdater<double> power);
|
|
AddMeasurement(
|
|
builder,
|
|
measurements.MassFlow!.NodeId,
|
|
EngineeringUnits.KilogramsPerSecond,
|
|
min: PumpDatasheet.Ranges.MassFlowMin,
|
|
max: PumpDatasheet.Ranges.MassFlowMax,
|
|
out IValueUpdater<double> flow);
|
|
AddMeasurement(
|
|
builder,
|
|
measurements.PumpEfficiency!.NodeId,
|
|
EngineeringUnits.Percent,
|
|
min: PumpDatasheet.Ranges.PumpEfficiencyMin,
|
|
max: PumpDatasheet.Ranges.PumpEfficiencyMax,
|
|
out IValueUpdater<double> efficiency);
|
|
AddMeasurement(
|
|
builder,
|
|
measurements.Level!.NodeId,
|
|
EngineeringUnits.Metre,
|
|
min: PumpDatasheet.Ranges.LevelMin,
|
|
max: PumpDatasheet.Ranges.LevelMax,
|
|
out IValueUpdater<double> level);
|
|
|
|
builder.Variable<uint>(measurements.NumberOfStarts!.NodeId)
|
|
.Bind(out IValueUpdater<uint> numberOfStarts)
|
|
.Historize(historyAccessLevel: AccessLevels.HistoryRead);
|
|
|
|
ushort pumpsNs = (ushort)Server.NamespaceUris.GetIndex(
|
|
Opc.Ua.Pumps.Namespaces.Pumps);
|
|
INodeBuilder<PumpState> pumpBuilder = builder.Node<PumpState>(pump.NodeId);
|
|
INodeBuilder<SupervisionState> events = pumpBuilder.Components().Events();
|
|
|
|
// The alarm reports the bearing-temperature chain, so its
|
|
// source node is the measurement and its limits are the
|
|
// datasheet trip points.
|
|
IAlarmBuilder<NonExclusiveLimitAlarmState> overTempAlarm = events
|
|
.CreateLimitAlarm(new QualifiedName("OverTempAlarm", pumpsNs))
|
|
.WithLimits(
|
|
highHigh: PumpDatasheet.TripPoints.BearingTemperatureHighHigh,
|
|
high: PumpDatasheet.TripPoints.BearingTemperatureHigh,
|
|
low: PumpDatasheet.TripPoints.BearingTemperatureLow,
|
|
lowLow: PumpDatasheet.TripPoints.BearingTemperatureLowLow)
|
|
.MonitorVariable(measurements.BearingTemperature)
|
|
.OnAcknowledge((ctx, c, eventId, comment) => ServiceResult.Good);
|
|
|
|
IVariableBuilder<bool> cavitationBuilder = events.Components()
|
|
.SupervisionProcessFluid()
|
|
.Components()
|
|
.Cavitation();
|
|
WireBoolean(
|
|
cavitationBuilder,
|
|
new LocalizedText("Cavitation"),
|
|
new LocalizedText("No cavitation"),
|
|
out IValueUpdater<bool> cavitation);
|
|
|
|
IVariableBuilder<bool> motorOverheatBuilder = events.Components()
|
|
.SupervisionPumpOperation()
|
|
.Components()
|
|
.MotorOverheat();
|
|
WireBoolean(
|
|
motorOverheatBuilder,
|
|
new LocalizedText("Motor overheat"),
|
|
new LocalizedText("No motor overheat"),
|
|
out IValueUpdater<bool> motorOverheat);
|
|
motorOverheatBuilder.ActivatesAlarm(overTempAlarm);
|
|
|
|
return new PumpSimulationState(
|
|
profileIndex,
|
|
SimulationInterval,
|
|
pressure,
|
|
fluidTemperature,
|
|
bearingTemperature,
|
|
power,
|
|
flow,
|
|
efficiency,
|
|
level,
|
|
numberOfStarts,
|
|
cavitation,
|
|
motorOverheat);
|
|
}
|
|
|
|
private static void AddMeasurement(
|
|
INodeManagerBuilder builder,
|
|
NodeId nodeId,
|
|
EUInformation units,
|
|
double min,
|
|
double max,
|
|
out IValueUpdater<double> updater)
|
|
{
|
|
builder.Variable<double>(nodeId)
|
|
.Bind(out updater)
|
|
.WithEngineeringUnits(units)
|
|
.WithEURange(min, max)
|
|
.Historize(
|
|
historyAccessLevel: AccessLevels.HistoryRead,
|
|
autoCapture: true,
|
|
captureOptions: s_historianCaptureOptions);
|
|
}
|
|
|
|
private static void WireBoolean(
|
|
IVariableBuilder<bool> variable,
|
|
LocalizedText trueState,
|
|
LocalizedText falseState,
|
|
out IValueUpdater<bool> updater)
|
|
{
|
|
variable.Bind(out updater)
|
|
.Historize(historyAccessLevel: AccessLevels.HistoryRead);
|
|
|
|
BaseVariableState variableState = variable.Node;
|
|
NodeState? trueStateNode = variableState.FindChild(
|
|
variable.Builder.Context,
|
|
new QualifiedName("TrueState"));
|
|
if (trueStateNode is BaseVariableState trueStateVariable)
|
|
{
|
|
trueStateVariable.WrappedValue = Variant.From(trueState);
|
|
}
|
|
|
|
NodeState? falseStateNode = variableState.FindChild(
|
|
variable.Builder.Context,
|
|
new QualifiedName("FalseState"));
|
|
if (falseStateNode is BaseVariableState falseStateVariable)
|
|
{
|
|
falseStateVariable.WrappedValue = Variant.From(falseState);
|
|
}
|
|
}
|
|
|
|
private static readonly HistorianCaptureOptions s_historianCaptureOptions = new()
|
|
{
|
|
MaxQueuedSamples = 8192,
|
|
BatchTarget = 128,
|
|
BatchWindow = TimeSpan.FromMilliseconds(50),
|
|
FullMode = CaptureFullMode.DropOldest
|
|
};
|
|
|
|
private void AdvanceSimulation()
|
|
{
|
|
long tick = Interlocked.Increment(ref m_simulationTicks);
|
|
foreach (PumpSimulationState simulation in m_pumpSimulations.Values)
|
|
{
|
|
simulation.Advance(tick);
|
|
}
|
|
PublishOpenUsdSignals();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds a Variable to the set the simulation tick publishes.
|
|
/// </summary>
|
|
/// <param name="variable">The variable to publish every tick.</param>
|
|
/// <param name="getter">Yields the latest value.</param>
|
|
/// <remarks>
|
|
/// The OpenUSD signals are created directly rather than through the
|
|
/// fluent builder, so they have no <see cref="IValueUpdater{TValue}"/>
|
|
/// of their own. A variable wired with only an <c>OnRead</c> handler
|
|
/// serves polled reads but never raises a data change, which leaves a
|
|
/// twin driven from a subscription rendering the start-up value
|
|
/// forever; publishing here is what makes monitored items observe them.
|
|
/// </remarks>
|
|
private void TrackSignal(BaseVariableState variable, Func<double> getter)
|
|
{
|
|
lock (m_simulationRegistrationLock)
|
|
{
|
|
m_liveSignals = [.. m_liveSignals, (variable, getter)];
|
|
}
|
|
}
|
|
|
|
private void PublishOpenUsdSignals()
|
|
{
|
|
DateTime now = DateTime.UtcNow;
|
|
foreach ((BaseVariableState variable, Func<double> getter) in
|
|
Volatile.Read(ref m_liveSignals))
|
|
{
|
|
variable.Value = getter();
|
|
variable.Timestamp = now;
|
|
variable.ClearChangeMasks(SystemContext, includeChildren: false);
|
|
}
|
|
|
|
foreach (PumpTwin twin in m_twins.Values)
|
|
{
|
|
BaseDataVariableState? alarm = twin.AlarmActive;
|
|
if (alarm != null)
|
|
{
|
|
alarm.Value = twin.AlarmActiveState;
|
|
alarm.Timestamp = now;
|
|
alarm.ClearChangeMasks(SystemContext, includeChildren: false);
|
|
}
|
|
|
|
BaseDataVariableState? surface = twin.FluidSurface;
|
|
if (surface != null)
|
|
{
|
|
surface.Value = new ExtensionObject(
|
|
FluidSurfaceAt(twin.Simulation?.LevelMetres ??
|
|
PumpDatasheet.Simulation.LevelNominal));
|
|
surface.Timestamp = now;
|
|
surface.ClearChangeMasks(SystemContext, includeChildren: false);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static class EngineeringUnits
|
|
{
|
|
public static readonly EUInformation Pascal =
|
|
new("Pa", "Pascal", "http://www.opcfoundation.org/UA/units/un/cefact");
|
|
|
|
public static readonly EUInformation Kelvin =
|
|
new("K", "Kelvin", "http://www.opcfoundation.org/UA/units/un/cefact");
|
|
|
|
public static readonly EUInformation Watt =
|
|
new("W", "Watt", "http://www.opcfoundation.org/UA/units/un/cefact");
|
|
|
|
public static readonly EUInformation KilogramsPerSecond =
|
|
new("kg/s", "Kilograms per Second", "http://www.opcfoundation.org/UA/units/un/cefact");
|
|
|
|
public static readonly EUInformation Percent =
|
|
new("%", "Percent", "http://www.opcfoundation.org/UA/units/un/cefact");
|
|
|
|
public static readonly EUInformation Metre =
|
|
new("m", "Metre", "http://www.opcfoundation.org/UA/units/un/cefact");
|
|
}
|
|
|
|
private sealed class PumpSimulationState
|
|
{
|
|
public PumpSimulationState(
|
|
int profileIndex,
|
|
TimeSpan tickInterval,
|
|
IValueUpdater<double> pressure,
|
|
IValueUpdater<double> fluidTemperature,
|
|
IValueUpdater<double> bearingTemperature,
|
|
IValueUpdater<double> power,
|
|
IValueUpdater<double> flow,
|
|
IValueUpdater<double> efficiency,
|
|
IValueUpdater<double> level,
|
|
IValueUpdater<uint> numberOfStarts,
|
|
IValueUpdater<bool> cavitation,
|
|
IValueUpdater<bool> motorOverheat)
|
|
{
|
|
m_phaseOffset =
|
|
profileIndex * PumpDatasheet.Simulation.PhaseOffsetTicks;
|
|
m_tickInterval = tickInterval;
|
|
m_pressure = pressure;
|
|
m_fluidTemperature = fluidTemperature;
|
|
m_bearingTemperature = bearingTemperature;
|
|
m_power = power;
|
|
m_flow = flow;
|
|
m_efficiency = efficiency;
|
|
m_level = level;
|
|
m_numberOfStarts = numberOfStarts;
|
|
m_cavitation = cavitation;
|
|
m_motorOverheat = motorOverheat;
|
|
}
|
|
|
|
public void Initialize(long tick)
|
|
{
|
|
Publish(tick, publishAll: true, StatusCodes.BadWaitingForInitialData);
|
|
}
|
|
|
|
public void Advance(long tick)
|
|
{
|
|
Publish(tick, publishAll: !m_hasPublishedGoodValue, StatusCodes.Good);
|
|
m_hasPublishedGoodValue = true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Publishes one simulation step. Volumetric flow is the only
|
|
/// independent variable; head, differential pressure, mass
|
|
/// flow, efficiency and shaft power all follow from the
|
|
/// datasheet characteristic curves, so the published values
|
|
/// stay mutually consistent.
|
|
/// </summary>
|
|
private void Publish(long tick, bool publishAll, StatusCode statusCode)
|
|
{
|
|
long localTick = tick + m_phaseOffset;
|
|
DateTime sourceTimestamp = DateTime.UtcNow;
|
|
|
|
double flow = PumpDatasheet.Hydraulics.RatedFlow *
|
|
(1.0 +
|
|
(PumpDatasheet.Simulation.FlowModulation *
|
|
Math.Sin(localTick * PumpDatasheet.Simulation.FlowRate)));
|
|
double head = Head(flow);
|
|
double efficiency = Efficiency(flow);
|
|
double massFlow = PumpDatasheet.Hydraulics.FluidDensity *
|
|
flow /
|
|
3600.0;
|
|
double differentialPressure =
|
|
PumpDatasheet.Hydraulics.FluidDensity *
|
|
PumpDatasheet.Hydraulics.GravitationalAcceleration *
|
|
head;
|
|
double shaftPower = differentialPressure * (flow / 3600.0) /
|
|
(efficiency / 100.0);
|
|
double bearingTemperature =
|
|
PumpDatasheet.Simulation.BearingTemperatureBase +
|
|
(PumpDatasheet.Simulation.BearingTemperatureLoadRise *
|
|
shaftPower /
|
|
PumpDatasheet.Hydraulics.RatedShaftPower) +
|
|
CoolingFaultExcursion(localTick);
|
|
double level = PumpDatasheet.Simulation.LevelNominal +
|
|
(PumpDatasheet.Simulation.LevelAmplitude *
|
|
Math.Sin(localTick * PumpDatasheet.Simulation.LevelRate));
|
|
Volatile.Write(ref m_levelMetres, level);
|
|
|
|
m_pressure.SetValue(differentialPressure, statusCode, sourceTimestamp);
|
|
m_flow.SetValue(massFlow, statusCode, sourceTimestamp);
|
|
m_efficiency.SetValue(efficiency, statusCode, sourceTimestamp);
|
|
m_power.SetValue(shaftPower, statusCode, sourceTimestamp);
|
|
m_bearingTemperature.SetValue(
|
|
bearingTemperature,
|
|
statusCode,
|
|
sourceTimestamp);
|
|
m_level.SetValue(level, statusCode, sourceTimestamp);
|
|
m_fluidTemperature.SetValue(
|
|
PumpDatasheet.Simulation.FluidTemperatureNominal +
|
|
(PumpDatasheet.Simulation.FluidTemperatureAmplitude *
|
|
Math.Sin(
|
|
localTick *
|
|
PumpDatasheet.Simulation.FluidTemperatureRate)),
|
|
statusCode,
|
|
sourceTimestamp);
|
|
|
|
// Integrate the shaft position from the running speed so the
|
|
// twin shows the pump actually turning. Speed follows flow, so
|
|
// the impeller visibly slows and picks up with the duty point.
|
|
// MassFlow is a rate: binding it straight to a rotation op
|
|
// would pin the shaft at a fraction of a degree instead.
|
|
// Unbounded on purpose - wrapping at 360 would make a client
|
|
// that interpolates between samples spin the shaft backwards
|
|
// across the wrap.
|
|
double rpm = PumpDatasheet.Hydraulics.RatedSpeed *
|
|
(massFlow / PumpDatasheet.Hydraulics.RatedMassFlow);
|
|
double seconds = m_tickInterval.TotalSeconds;
|
|
Volatile.Write(
|
|
ref m_shaftAngle,
|
|
Volatile.Read(ref m_shaftAngle) + (rpm * 6.0 * seconds));
|
|
|
|
uint numberOfStarts = checked((uint)(localTick /
|
|
PumpDatasheet.Simulation.StartIntervalTicks));
|
|
if (publishAll || numberOfStarts != m_currentNumberOfStarts)
|
|
{
|
|
m_currentNumberOfStarts = numberOfStarts;
|
|
m_numberOfStarts.SetValue(numberOfStarts, statusCode, sourceTimestamp);
|
|
}
|
|
|
|
// Cavitation is reported once the suction head falls below
|
|
// the NPSH requirement, with hysteresis so the supervision
|
|
// state does not chatter at the threshold.
|
|
bool cavitation = m_currentCavitation
|
|
? level < PumpDatasheet.TripPoints.CavitationClearLevel
|
|
: level < PumpDatasheet.TripPoints.CavitationSetLevel;
|
|
if (publishAll || cavitation != m_currentCavitation)
|
|
{
|
|
m_currentCavitation = cavitation;
|
|
m_cavitation.SetValue(cavitation, statusCode, sourceTimestamp);
|
|
}
|
|
|
|
bool motorOverheat = m_currentMotorOverheat
|
|
? bearingTemperature >=
|
|
PumpDatasheet.TripPoints.MotorOverheatClear
|
|
: bearingTemperature >=
|
|
PumpDatasheet.TripPoints.MotorOverheatSet;
|
|
if (publishAll || motorOverheat != m_currentMotorOverheat)
|
|
{
|
|
m_currentMotorOverheat = motorOverheat;
|
|
m_motorOverheat.SetValue(motorOverheat, statusCode, sourceTimestamp);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Head curve of the datasheet, in m for a flow in m³/h.
|
|
/// </summary>
|
|
private static double Head(double flow)
|
|
{
|
|
return PumpDatasheet.Hydraulics.ShutoffHead -
|
|
(PumpDatasheet.Hydraulics.HeadCurveCoefficient * flow * flow);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Efficiency curve of the datasheet, in percent for a flow in
|
|
/// m³/h.
|
|
/// </summary>
|
|
private static double Efficiency(double flow)
|
|
{
|
|
double deviation =
|
|
(flow - PumpDatasheet.Hydraulics.RatedFlow) /
|
|
PumpDatasheet.Hydraulics.RatedFlow;
|
|
return PumpDatasheet.Hydraulics.RatedEfficiency *
|
|
(1.0 -
|
|
(PumpDatasheet.Hydraulics.EfficiencyCurveFactor *
|
|
deviation *
|
|
deviation));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Bearing temperature rise in K caused by the periodic
|
|
/// bearing-cooling interruption documented in the datasheet.
|
|
/// The ramp crosses both the high and the high-high trip point
|
|
/// so a complete alarm cycle is observable.
|
|
/// </summary>
|
|
private static double CoolingFaultExcursion(long tick)
|
|
{
|
|
long cycle = tick % PumpDatasheet.Simulation.CoolingFaultPeriodTicks;
|
|
if (cycle < PumpDatasheet.Simulation.CoolingFaultOnsetTick)
|
|
{
|
|
return 0.0;
|
|
}
|
|
const long rampTicks = PumpDatasheet.Simulation.CoolingFaultPeriodTicks -
|
|
PumpDatasheet.Simulation.CoolingFaultOnsetTick;
|
|
return PumpDatasheet.Simulation.CoolingFaultRise *
|
|
(cycle - PumpDatasheet.Simulation.CoolingFaultOnsetTick) /
|
|
rampTicks;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Shaft angular position in degrees, integrated from the running
|
|
/// speed. Drives the OpenUSD rotation binding.
|
|
/// </summary>
|
|
public double ShaftAngleDegrees => Volatile.Read(ref m_shaftAngle);
|
|
|
|
/// <summary>
|
|
/// The supervision state the OpenUSD status-light binding follows.
|
|
/// </summary>
|
|
public bool AlarmActive => m_currentCavitation || m_currentMotorOverheat;
|
|
|
|
/// <summary>
|
|
/// Suction vessel level in metres, as last published. Drives the
|
|
/// OpenUSD liquid-surface binding.
|
|
/// </summary>
|
|
public double LevelMetres => Volatile.Read(ref m_levelMetres);
|
|
|
|
private readonly long m_phaseOffset;
|
|
private readonly TimeSpan m_tickInterval;
|
|
private readonly IValueUpdater<double> m_pressure;
|
|
private readonly IValueUpdater<double> m_fluidTemperature;
|
|
private readonly IValueUpdater<double> m_bearingTemperature;
|
|
private readonly IValueUpdater<double> m_power;
|
|
private readonly IValueUpdater<double> m_flow;
|
|
private readonly IValueUpdater<double> m_efficiency;
|
|
private readonly IValueUpdater<double> m_level;
|
|
private readonly IValueUpdater<uint> m_numberOfStarts;
|
|
private readonly IValueUpdater<bool> m_cavitation;
|
|
private readonly IValueUpdater<bool> m_motorOverheat;
|
|
private uint m_currentNumberOfStarts;
|
|
private bool m_currentCavitation;
|
|
private bool m_currentMotorOverheat;
|
|
private double m_shaftAngle;
|
|
private double m_levelMetres;
|
|
private bool m_hasPublishedGoodValue;
|
|
}
|
|
|
|
private readonly ConcurrentDictionary<NodeId, PumpSimulationState> m_pumpSimulations = new();
|
|
private readonly Lock m_simulationRegistrationLock = new();
|
|
private long m_simulationTicks;
|
|
private int m_nextSimulationProfile;
|
|
|
|
/// <summary>
|
|
/// Measurement Variables created outside the fluent builder, paired
|
|
/// with the getter that yields their latest simulated value.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Held as an immutable snapshot that <see cref="TrackSignal"/> replaces
|
|
/// under <see cref="m_simulationRegistrationLock"/>. A pump can be added
|
|
/// through <c>CreatePumpAsync</c> while the simulation timer is running,
|
|
/// and mutating a list while the tick enumerates it would throw on the
|
|
/// timer thread and stop the simulation for every pump. Publishing from a
|
|
/// snapshot keeps the tick allocation-free and lock-free.
|
|
/// </remarks>
|
|
private (BaseVariableState Variable, Func<double> Getter)[] m_liveSignals = [];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Defines log messages for configuring the pump node manager.
|
|
/// </summary>
|
|
internal static partial class PumpNodeManagerLog
|
|
{
|
|
/// <summary>
|
|
/// Logs the start of fluent pump node manager configuration.
|
|
/// </summary>
|
|
[LoggerMessage(EventId = PumpDeviceIntegrationServerEventIds.PumpNodeManager + 0,
|
|
Level = LogLevel.Information,
|
|
Message = "Configuring PumpNodeManager fluent wiring...")]
|
|
public static partial void ConfiguringPumpNodeManagerFluentWiring(this ILogger logger);
|
|
}
|
|
}
|