mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-18 22:55:08 +08:00
ca89ac85a7
# Description Adds a **Generators companion-specification sample** alongside the existing pump sample, and a **`SiteCompositionServer`** that composes several device servers into one OpenUSD scene at a supervisory level — demonstrating that servers can be aggregated without mirroring their address spaces. Three things, in dependency order: ### 1. `GeneratorServer` A self-contained server realising the draft Generators spec (`http://opcfoundation.org/UA/Generators/`) end to end: N simulated generating sets, DI + Machinery integration, a twelve-state operating state machine, four protection alarms per set, six control methods, and a per-set OpenUSD twin. The organising idea is that **load fraction is the only independent variable**. Everything else is a function of it: ``` V̇_f(x) = 3.67 + 100·x fuel rate [L/h] η(x) = P(x) / (V̇_f(x) · ρ · LHV) efficiency S = P / PF I = S / (√3·V_LL) f = N·p / 120 ``` This is not stylistic. When each measurement is an independent oscillator — as the pump sample's simulation once was — a server happily publishes a duty point no real machine could occupy, and no test can catch it because there is nothing for the values to be inconsistent *with*. Deriving them from one variable means `P = √3·V·I·PF` and `η = P/(V̇·ρ·LHV)` hold at every tick by construction. The published `DATASHEET.md`, the engineering ranges, the trip points and the simulation all read the same constants in `GeneratorDatasheet.cs`, so the document and the server cannot describe different machines. The machine is a fictitious **SimGen Systems GenX-500** (400 kW prime / 440 kW standby, 400/230 V, 50 Hz, four-pole). Figures are representative of a real industrial genset class; no vendor is named anywhere in the code or docs. ### 2. Cross-server composition in the connector `RemoteSessionFactory` already existed in the client library but the connector CLI never set it, so cross-server composition was unreachable. `--federate` wires it up: the connector opens a session to each server named by a component binding, discovers its representations and drives its bindings into the same stage. It is **opt-in** because the endpoint the connector dials comes from the server being rendered rather than from the operator, which makes honouring it a trust decision. Federation is best-effort per component — a subordinate that is down is logged and skipped, and the rest of the scene still renders — which is the only `src/` change in this PR. ### 3. `SiteCompositionServer` Owns no devices. It publishes a site stage plus one cross-server component binding per subordinate, carrying that server's `ComponentServerUri` and `ComponentEndpointUrl`. Nothing is mirrored, so there is no cache to invalidate and no second copy of the truth. ## Notes for reviewers **Everything interesting in this PR was found by running the servers, not by reading the code.** Six defects, none of which looked wrong in review: - `IsShutdown` and `SubsystemName` are *optional* on `GeneratorProtectionAlarmType`, so the generated factory does not materialise them. `CreateOrReplace` alone produces a child that exists, appears in `GetChildren` and holds the right value — but carries **no `ReferenceTypeId`**, so no browse can reach it. Every alarm was publishing its trip without saying whether the trip stops the machine or which subsystem to go to. `AddXxx(context)` first is what gives the child its `HasProperty` reference. - **The protections could never fire.** Every trip point sits outside the band the datasheet curves produce — that is what a datasheet *means* — so all four alarms, the shutdown class, `ResetFaults` and the whole `Fault` branch of the state machine were unreachable while the README documented them as observable. Overload was worse: the load clamp ceiling was set to exactly the trip point, making a strictly-greater-than comparison unsatisfiable. Faults are now injectable, and the first set — the one the hero camera frames — develops one on a slow rotation. - **A shutdown trip removes the condition that caused it**, because oil pressure and coolant temperature are only supervised while the engine turns. Each alarm went active for one tick and cleared, leaving an operator with a stopped machine and no indication of why. Shutdown-class alarms now latch until the set leaves the shutdown state. Every unit test that checked the *condition* passed throughout — the defect only appears when the trip and the supervision interact over time. - **`Synchronizing` and `Paralleled` were declared, drawn in the README and never entered.** The first set now energises a dead bus and closes onto it while every other set synchronises to a live one — both how a real plant parallels, and what makes the two states observable. - **The tick raced client method calls.** The simulation tick runs on a thread-pool thread while method calls arrive on request threads, and both transition sets and write the same nodes. A tick moving a set to `Cooldown` and a concurrent `EmergencyStop` could interleave the paired `CurrentState` / `CurrentState.Id` writes and leave a client with a state *name* from one transition and a state *node* from the other — the exact failure the paired write exists to prevent, reintroduced by the threading model. Both paths now take one gate. - Low oil pressure supervised from raw speed **tripped every set during cranking**, because pressure has not built yet. Now gated on `IsSpinning`, which is what a real start-up bypass does. Smaller fixes: shutdown trips are applied after the whole evaluation pass (stopping mid-loop made the remaining conditions read healthy, collapsing simultaneous trips to whichever came first in the table); `ResetFaults` reports its clears as events (a client learns of condition state changes only through events, so a silent clear leaves an alarm-list client showing it forever); the start counter moved into the transition so commanded starts are counted; the federated connector closes the remote session if the connector constructor throws between taking ownership and registering it; and `prepare_machinery_nodeset.py` now *asserts* the IA namespace is last before removing it rather than only claiming so in its docstring — removing any earlier entry would silently renumber every namespace after it and rebind their NodeIds. **A model limitation is left visible rather than papered over.** `GeneratorStateMachineType` declares an emergency stop only out of `Running`, `Loaded` and `Paralleled`, so the sample refuses `EmergencyStop` from `Starting` and `Warmup`. A real panel stops from anywhere. That is the specification's shape, not this sample's choice, so it is pinned by a test and named in the docs. **`Model/` vendors a reduced Machinery nodeset**, derived mechanically by whitelist. The full official nodeset does not survive the model source generator (`MODELGEN003`) and drags in IA through a single optional `Stacklight` member a generating set does not have. Deriving it by script keeps the provenance checkable; the whitelist is the only thing to edit when more types are needed. **Never hand-edit the generated output.** **The federated scene renders end to end.** Getting there surfaced three more defects, all of which produced a plausible-looking scene with nothing in it: the generator sample's plant aggregation was created under an already-registered `DeviceSet` and so was invisible to every client (it had *never* rendered geometry, standalone or federated); the connector's asset fetch ran on the primary session only, so composition referenced layers that were never downloaded; and both generator colour bindings wrote `primvars:displayColor` to prims that did not declare it, so the renderer rejected every update while the file still looked correct. Cross-server components compose under the subordinate's own root, so the site layer now *places* `/Plant` and `/Powerhouse` rather than leaving them stacked on the origin. **`OpenUsdRepresentation` is now mounted with `HasAddIn`, not `HasComponent`** (review feedback). The nodeset says so explicitly — *"Mounted with HasAddIn"* — but every server in the tree used plain `HasComponent`. It survived because `HasAddIn` is a *subtype* of `HasComponent`: the representation still browses, still aggregates and still drives a twin, so every functional test passed before the fix and after it, and only a conformance checker could tell. Seven mount sites corrected. `PumpDeviceIntegrationServer` and `MinimalRobotServer` had hand-rolled the mount instead of calling the shared `CreateRepresentation` helper, which is exactly how they drifted from it. Both sample E2E suites now assert the reference type across **every** discovered representation — a narrower check would have missed the plant-level representation that arrived later from master still carrying `HasComponent`. **Live colour is not achievable in the current OpenUSD viewer, and that is now documented rather than worked around.** Proven with a standalone probe: `primvars:displayColor` resolves as `color3f[]` from the `UsdGeomGprim` schema whatever the layer declares, and the `OpenUsd 0.4.0-alpha` managed API has no writer for that type. Bound `UsdPreviewSurface` materials are not shaded either, so geometry renders grey unless it also carries an explicit `displayColor` primvar. The **visibility** bindings carry no such caveat and are what the samples rely on to show state. Filed upstream as [openusd-dotnet#2](https://github.com/marcschier/openusd-dotnet/issues/2), [#3](https://github.com/marcschier/openusd-dotnet/issues/3) and [#4](https://github.com/marcschier/openusd-dotnet/issues/4), and linked from `docs/OpenUsd.md` so a reader can check whether they have since been fixed. ## Related Issues No tracking issue — this is additive sample and documentation work with a single small, self-contained change to `src/` (per-component error isolation and session-ownership hardening in `OpenUsdConnector.Composition.cs`). Happy to open one if maintainers would prefer it tracked. ## 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. - [x] 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. ### Testing The generator fixtures live in `tests/Opc.Ua.OpenUsd.Tests/Generator` — **82 tests**, no new project. `Opc.Ua.Di.Tests` would have been the natural home next to the pump fixtures, but both device samples source-generate their own reduced `Opc.Ua.Machinery` model and expose it via `InternalsVisibleTo`, so referencing both from one assembly makes every Machinery type ambiguous (CS0433); `Opc.Ua.OpenUsd.Tests` references no other sample and already hosts `RobotAssetContractTests`. The suite runs **870** on net10.0 and net48 (784 existing + 86) and **788** on net472, where the sample does not exist and only the framework-independent asset-contract tests run — forgetting exactly that exclusion broke CI on the sibling pump PR. The tests target the things in this sample that fail *quietly*: - **Datasheet conformance** holds the model to its own claim — rated speed is `120·f/p`, rated current follows from the rating, the fuel curve reproduces the published table, and `η = P/(V̇·ρ·LHV)` reconciles at every load. Efficiency is swept across the whole simulated range to show it stays inside (0,100) and rises monotonically; a fit that goes negative somewhere in its range is a coincidence that happens to look right at the duty point, not a model. A further test reads `DATASHEET.md` and checks the document quotes the figures the server actually serves. - **Drift between the two descriptions of the state machine** — the physics' `IsLegalTransition` and the model's `GeneratorStateMap` — is checked in *both* directions. A transition the physics permits but the map lacks moves a machine without telling a client; one the map holds but the physics refuses is dead weight that looks supported. - **Reachability at run time**, not just in the declared table — the test that catches states the model declares and nothing ever enters. - **That every protection can actually fire**, which is the half of the alarm contract that "a healthy set annunciates nothing" does not cover. A **hosted end-to-end fixture** connects a real client and asserts what the address space actually exposes — the aggregation at `/Powerhouse/Generators`, its component binding, and every per-set twin. That is the only kind of test that catches the registration defect above: the node object had the right browse name, binding and asset reference, so every test that inspected objects passed while no client could see it. **Every state-machine and protection fix was checked by mutation.** Restoring the clamp ceiling, the direct `Running → Loaded` path, the old start-counter placement, or removing the alarm opt-in each makes the corresponding test fail, naming the specific defect. A test that has never been seen to fail has not been shown to work. Verified against a running plant: `Synchronizing`, `Paralleled` and `Fault` all observed on a two-set server, with `HighCoolantTemperatureAlarm` seen active on the fault subject. Method behaviour verified separately — per-set distinct `CurrentState` nodes, `EmergencyStop` → `EmergencyStopped` with `Start` then refused as `BadInvalidState`, `ResetFaults` → `Off`, `SetOperatingMode(9999)` refused with the mode unchanged, and the other sets untouched throughout. Also verified as a three-server federated stage. 0 warnings on a clean Release rebuild of both samples, the client library, the connector and the tests, across every TFM. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: fe608993-f3c9-4779-a6b9-9a9eabfc24ba
606 lines
26 KiB
C#
606 lines
26 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.Generic;
|
|
using System.Globalization;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Di;
|
|
using Opc.Ua.Di.Server;
|
|
using Opc.Ua.Di.Server.Builders;
|
|
using Opc.Ua.Di.Server.Hosting;
|
|
using Opc.Ua.Generators;
|
|
using Opc.Ua.Machinery;
|
|
using Opc.Ua.OpenUsd;
|
|
using Opc.Ua.Server;
|
|
using Opc.Ua.Server.Fluent;
|
|
using Opc.Ua.Server.NodeManager;
|
|
|
|
namespace Generators
|
|
{
|
|
/// <summary>
|
|
/// Runtime options for the generator-set device-integration sample.
|
|
/// </summary>
|
|
public sealed class GeneratorDeviceIntegrationOptions
|
|
{
|
|
/// <summary>
|
|
/// Gets or sets how many simulated generator sets are materialised.
|
|
/// </summary>
|
|
public int GeneratorCount { get; set; } = 2;
|
|
|
|
/// <summary>
|
|
/// Gets or sets the interval used by the live simulation loop.
|
|
/// </summary>
|
|
public TimeSpan SimulationInterval { get; set; } = TimeSpan.FromMilliseconds(250);
|
|
|
|
/// <summary>
|
|
/// Gets or sets whether one set develops faults on a slow rotation.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// On by default. A set running to its datasheet stays well inside every
|
|
/// trip point, so without a deliberate excursion the protection alarms, the
|
|
/// shutdown class and the Fault branch of the state machine are all code
|
|
/// that never runs. Turn it off to watch a plant that is purely healthy.
|
|
/// </remarks>
|
|
public bool InjectFaults { get; set; } = true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Node manager for the Generators companion-specification server.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// This partial carries the infrastructure - construction, address-space load
|
|
/// and instance materialisation. The datasheet-driven simulation, the twelve
|
|
/// state operating state machine and the protection alarms live in
|
|
/// <c>GeneratorNodeManager.Configure.cs</c>; the OpenUSD twin lives in
|
|
/// <c>OpenUsdRepresentation.cs</c>.
|
|
/// </para>
|
|
/// <para>
|
|
/// Unlike the pump sample - whose <c>PumpType</c> derives from the Machinery
|
|
/// <c>MachineType</c> and so cannot use the DI device helpers -
|
|
/// <c>GeneratorSetType</c> derives from the DI <c>DeviceType</c>, so sets are
|
|
/// created through <see cref="DiNodeManager.CreateDeviceAsync{TDevice}"/> and
|
|
/// get the DI nameplate, registration and topology wiring for free.
|
|
/// </para>
|
|
/// </remarks>
|
|
public partial class GeneratorNodeManager : DiNodeManager
|
|
{
|
|
private readonly GeneratorDeviceIntegrationOptions m_options;
|
|
private readonly List<GeneratorSetState> m_generatorSets = [];
|
|
|
|
/// <summary>
|
|
/// Wires the simulation, state machines and alarms against the
|
|
/// materialised instances. Implemented in
|
|
/// <c>GeneratorNodeManager.Configure.cs</c>.
|
|
/// </summary>
|
|
/// <param name="builder">The active fluent builder.</param>
|
|
partial void Configure(INodeManagerBuilder builder);
|
|
|
|
/// <summary>
|
|
/// Initialises a new <see cref="GeneratorNodeManager"/> without DI-hosting
|
|
/// integration.
|
|
/// </summary>
|
|
/// <param name="server">The server the manager belongs to.</param>
|
|
/// <param name="configuration">The application configuration.</param>
|
|
public GeneratorNodeManager(
|
|
IServerInternal server,
|
|
ApplicationConfiguration configuration)
|
|
: this(server, configuration, postSetupRunner: null, options: null)
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// Initialises a new <see cref="GeneratorNodeManager"/> that participates in
|
|
/// the DI hosting post-setup pipeline.
|
|
/// </summary>
|
|
/// <param name="server">The server the manager belongs to.</param>
|
|
/// <param name="configuration">The application configuration.</param>
|
|
/// <param name="postSetupRunner">Optional DI post-setup pipeline.</param>
|
|
/// <param name="options">Optional sample options.</param>
|
|
/// <exception cref="ArgumentOutOfRangeException">
|
|
/// The configured generator count or simulation interval is out of range.
|
|
/// </exception>
|
|
public GeneratorNodeManager(
|
|
IServerInternal server,
|
|
ApplicationConfiguration configuration,
|
|
IDiPostSetupRunner? postSetupRunner,
|
|
IOptions<GeneratorDeviceIntegrationOptions>? options = null)
|
|
: base(
|
|
server,
|
|
configuration,
|
|
postSetupRunner,
|
|
Opc.Ua.Generators.Namespaces.Generators,
|
|
Opc.Ua.Machinery.Namespaces.Machinery,
|
|
Opc.Ua.OpenUsd.Namespaces.OpenUSD)
|
|
{
|
|
// The base constructor points SystemContext.NodeIdFactory at itself;
|
|
// the New() override below takes over so every instance child gets a
|
|
// NodeId derived from its parent rather than the type-level one.
|
|
SystemContext.NodeIdFactory = this;
|
|
m_options = options?.Value ?? new GeneratorDeviceIntegrationOptions();
|
|
if (m_options.GeneratorCount is < 1 or > 100)
|
|
{
|
|
throw new ArgumentOutOfRangeException(
|
|
$"{nameof(options)}.{nameof(GeneratorDeviceIntegrationOptions.GeneratorCount)}",
|
|
m_options.GeneratorCount,
|
|
"Generator count must be between 1 and 100.");
|
|
}
|
|
if (m_options.SimulationInterval <= TimeSpan.Zero)
|
|
{
|
|
throw new ArgumentOutOfRangeException(
|
|
$"{nameof(options)}.{nameof(GeneratorDeviceIntegrationOptions.SimulationInterval)}",
|
|
m_options.SimulationInterval,
|
|
"Simulation interval must be positive.");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the registered generator-set instance NodeIds.
|
|
/// </summary>
|
|
public ArrayOf<NodeId> GeneratorNodeIds
|
|
{
|
|
get
|
|
{
|
|
var nodeIds = new List<NodeId>(m_generatorSets.Count);
|
|
foreach (GeneratorSetState set in m_generatorSets)
|
|
{
|
|
nodeIds.Add(set.NodeId);
|
|
}
|
|
return nodeIds.ToArrayOf();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the interval the simulation loop ticks at.
|
|
/// </summary>
|
|
internal TimeSpan SimulationInterval => m_options.SimulationInterval;
|
|
|
|
/// <summary>
|
|
/// Gets whether the fault schedule is running.
|
|
/// </summary>
|
|
internal bool InjectFaults => m_options.InjectFaults;
|
|
|
|
/// <inheritdoc/>
|
|
public override NodeId New(ISystemContext context, NodeState node)
|
|
{
|
|
if (node is BaseInstanceState { Parent: not null } instance)
|
|
{
|
|
string parentId = instance.Parent.NodeId.IdentifierAsString;
|
|
return new NodeId(
|
|
$"{parentId}_{instance.SymbolicName}",
|
|
InstanceNamespaceIndex);
|
|
}
|
|
return node.NodeId;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates and registers a generator set organised by the DI
|
|
/// <c>DeviceSet</c>, wired into the running simulation.
|
|
/// </summary>
|
|
/// <param name="browseName">Browse name for the new set.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>The registered generator set.</returns>
|
|
public ValueTask<GeneratorSetState> CreateGeneratorSetAsync(
|
|
QualifiedName browseName,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
return MaterialiseGeneratorSetAsync(
|
|
browseName,
|
|
m_generatorSets.Count + 1,
|
|
cancellationToken,
|
|
RegisterGeneratorSimulation);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
protected override ValueTask<NodeStateCollection> LoadPredefinedNodesAsync(
|
|
ISystemContext context,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
// Compose the predefined-node tree from the source-generated models in
|
|
// dependency order. No runtime XML loading: the NodeSet2 XMLs ship only
|
|
// as <AdditionalFiles> for the source generator. The generated AddOpcUa*
|
|
// methods are idempotent and pull in their declared dependencies through
|
|
// [ModelDependencyAttribute], so a direct chain is sufficient.
|
|
var nodes = new NodeStateCollection();
|
|
nodes.AddOpcUaDi(context);
|
|
nodes.AddOpcUaMachinery(context);
|
|
nodes.AddOpcUaGenerators(context);
|
|
nodes.AddOpcUaOpenUsd(context);
|
|
return new ValueTask<NodeStateCollection>(nodes);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
protected override async ValueTask OnAddressSpaceReadyAsync(
|
|
CancellationToken cancellationToken)
|
|
{
|
|
// Phase 1 (async): materialise the instances the fluent Configure pass
|
|
// expects to find, so the builder has typed nodes to wire against.
|
|
await ConfigureInstancesAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
// Phase 2 (sync): wire the simulation, state machines and alarms.
|
|
CreateFluentBuilder(InstanceNamespaceIndex)
|
|
.Configure(Configure)
|
|
.Seal();
|
|
|
|
m_logger.GeneratorAddressSpaceReady(PredefinedNodes.Count, m_generatorSets.Count);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Materialises the configured generator sets and the OpenUSD facility.
|
|
/// </summary>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
private async ValueTask ConfigureInstancesAsync(CancellationToken cancellationToken)
|
|
{
|
|
// The OpenUSD facility comes first so each set's representation has a
|
|
// stage to reference.
|
|
await MaterialiseOpenUsdFacilityAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
for (int number = 1; number <= m_options.GeneratorCount; number++)
|
|
{
|
|
var browseName = new QualifiedName(
|
|
GetGeneratorBrowseName(number),
|
|
InstanceNamespaceIndex);
|
|
await MaterialiseGeneratorSetAsync(browseName, number, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
}
|
|
|
|
await OrganiseRepresentationsAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates one generator set, materialises the optional subsystems the
|
|
/// simulation drives, attaches its OpenUSD twin and registers the whole
|
|
/// subtree.
|
|
/// </summary>
|
|
/// <param name="browseName">Browse name for the set.</param>
|
|
/// <param name="setNumber">One-based unit number, used for the nameplate.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <param name="onRegistered">Invoked once the set is registered.</param>
|
|
/// <returns>The registered generator set.</returns>
|
|
private async ValueTask<GeneratorSetState> MaterialiseGeneratorSetAsync(
|
|
QualifiedName browseName,
|
|
int setNumber,
|
|
CancellationToken cancellationToken,
|
|
Action<GeneratorSetState>? onRegistered = null)
|
|
{
|
|
IDeviceBuilder<GeneratorSetState> builder = await CreateDeviceAsync(
|
|
browseName,
|
|
NodeId.Create(
|
|
Opc.Ua.Generators.ObjectTypes.GeneratorSetType,
|
|
Opc.Ua.Generators.Namespaces.Generators,
|
|
Server.NamespaceUris),
|
|
parent => SystemContext.CreateInstanceOfGeneratorSetType(parent, browseName),
|
|
parent: null,
|
|
cancellationToken).ConfigureAwait(false);
|
|
|
|
GeneratorSetState set = builder.Device;
|
|
set.DisplayName = new LocalizedText(GetGeneratorDisplayName(setNumber));
|
|
|
|
MaterialiseOptionalChildren(set);
|
|
MaterialiseProtectionAlarms(set);
|
|
AttachOpenUsdRepresentation(set, setNumber);
|
|
|
|
await AddPredefinedNodeAsync(SystemContext, set, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
await AddRootNotifierAsync(set, cancellationToken).ConfigureAwait(false);
|
|
|
|
// The nameplate is written after the subtree is registered. Each
|
|
// identification property registers itself as it is created, so writing
|
|
// beforehand lets the subsequent subtree registration replace those
|
|
// nodes with freshly materialised, valueless ones - the properties then
|
|
// browse but read BadNotReadable.
|
|
WriteNameplate(builder, setNumber);
|
|
|
|
onRegistered?.Invoke(set);
|
|
|
|
// Variables hand-built onto the set (rather than materialised by the
|
|
// generated factory) browse and read correctly, but a monitored item
|
|
// never samples them unless they are registered in their own right.
|
|
await RegisterOpenUsdSignalsAsync(set, cancellationToken).ConfigureAwait(false);
|
|
|
|
m_generatorSets.Add(set);
|
|
m_logger.MaterialisedGeneratorSet(browseName.Name, set.NodeId);
|
|
return set;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Writes the datasheet nameplate onto the DI identification properties.
|
|
/// </summary>
|
|
/// <param name="builder">Device builder for the set.</param>
|
|
/// <param name="setNumber">One-based unit number.</param>
|
|
/// <remarks>
|
|
/// Unit-level fields are derived from the set number so that
|
|
/// <c>--generators N</c> yields a consistent nameplate per instance rather
|
|
/// than N copies of the same serial number.
|
|
/// </remarks>
|
|
private static void WriteNameplate(IDeviceBuilder<GeneratorSetState> builder, int setNumber)
|
|
{
|
|
builder.WithIdentification(id =>
|
|
{
|
|
id.Manufacturer = new LocalizedText(GeneratorDatasheet.Identity.Manufacturer);
|
|
id.ManufacturerUri = GeneratorDatasheet.Identity.ManufacturerUri;
|
|
id.Model = new LocalizedText(GeneratorDatasheet.Identity.Model);
|
|
id.ProductCode = GeneratorDatasheet.Identity.ProductCode;
|
|
id.HardwareRevision = GeneratorDatasheet.Identity.HardwareRevision;
|
|
id.SoftwareRevision = GeneratorDatasheet.Identity.SoftwareRevision;
|
|
id.DeviceRevision = GeneratorDatasheet.Identity.DeviceRevision;
|
|
id.SerialNumber = GetSerialNumber(setNumber);
|
|
id.DeviceManual = "https://simgen.example.com/genx-500/manual";
|
|
id.ProductInstanceUri = FormattableString.Invariant($"urn:simgen.example.com:GenX-500:{GetSerialNumber(setNumber)}");
|
|
});
|
|
|
|
// Nameplate properties the generated factory already materialised keep
|
|
// the declaration's access level, which grants no read. Only properties
|
|
// the builder creates itself come out readable, so the ones that were
|
|
// already there have to be opened explicitly or they browse but answer
|
|
// BadNotReadable.
|
|
GeneratorSetState set = builder.Device;
|
|
MakeReadable(
|
|
set.Manufacturer, set.ManufacturerUri, set.Model, set.ProductCode,
|
|
set.HardwareRevision, set.SoftwareRevision, set.DeviceRevision,
|
|
set.SerialNumber, set.DeviceManual, set.ProductInstanceUri,
|
|
set.RevisionCounter);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Grants current-read access to variables that carry a static value.
|
|
/// </summary>
|
|
/// <param name="variables">The variables to open for reading.</param>
|
|
private static void MakeReadable(params BaseVariableState?[] variables)
|
|
{
|
|
foreach (BaseVariableState? variable in variables)
|
|
{
|
|
if (variable == null)
|
|
{
|
|
continue;
|
|
}
|
|
variable.AccessLevel = AccessLevels.CurrentRead;
|
|
variable.UserAccessLevel = AccessLevels.CurrentRead;
|
|
variable.MinimumSamplingInterval = MinimumSamplingIntervals.Indeterminate;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Materialises the optional <c>GeneratorSetType</c> children the simulation
|
|
/// drives. Mandatory children - Identification, OperatingState, OperatingMode,
|
|
/// Engine, Alternator and Controller - are created by the generated factory.
|
|
/// </summary>
|
|
/// <param name="set">The generator set to extend.</param>
|
|
private void MaterialiseOptionalChildren(GeneratorSetState set)
|
|
{
|
|
set.AddMachineryBuildingBlocks(SystemContext)
|
|
.AddFuelSystem(SystemContext)
|
|
.AddCoolingSystem(SystemContext)
|
|
.AddLubricationSystem(SystemContext)
|
|
.AddStartingSystem(SystemContext)
|
|
.AddEmissionsStandard(SystemContext)
|
|
.AddApplication(SystemContext)
|
|
.AddGeneratorBreakerClosed(SystemContext)
|
|
.AddGeneratorBreakerAvailable(SystemContext)
|
|
.AddRemoteStartInput(SystemContext)
|
|
.AddRunRequest(SystemContext)
|
|
.AddLoadInhibit(SystemContext)
|
|
.AddAvailableToLoad(SystemContext)
|
|
.AddStart(SystemContext)
|
|
.AddStop(SystemContext)
|
|
.AddEmergencyStop(SystemContext)
|
|
.AddResetFaults(SystemContext)
|
|
.AddSetOperatingMode(SystemContext)
|
|
.AddStartTest(SystemContext);
|
|
|
|
MaterialiseSubsystemChildren(set);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Materialises the optional subsystem members the simulation publishes.
|
|
/// </summary>
|
|
/// <param name="set">The generator set to extend.</param>
|
|
/// <remarks>
|
|
/// The specification makes most telemetry optional so the type fits both a
|
|
/// bare air-cooled residential set and a fully instrumented industrial one.
|
|
/// This sample models the instrumented case, so it opts in explicitly rather
|
|
/// than assuming the factory materialises them.
|
|
/// </remarks>
|
|
private void MaterialiseSubsystemChildren(GeneratorSetState set)
|
|
{
|
|
set.Engine!
|
|
.AddPercentLoad(SystemContext)
|
|
.AddOilPressure(SystemContext)
|
|
.AddOilTemperature(SystemContext)
|
|
.AddCoolantTemperature(SystemContext)
|
|
.AddFuelRate(SystemContext)
|
|
.AddExhaustGasTemperature(SystemContext)
|
|
.AddIntakeManifoldTemperature(SystemContext)
|
|
.AddNumberOfStarts(SystemContext)
|
|
.AddDisplacement(SystemContext)
|
|
.AddCylinderCount(SystemContext)
|
|
.AddRatedSpeed(SystemContext)
|
|
.AddAspiration(SystemContext);
|
|
|
|
// Three-phase set: L1 is mandatory, L2 and L3 are not.
|
|
set.Alternator!
|
|
.AddL2(SystemContext)
|
|
.AddL3(SystemContext)
|
|
.AddAverageLineToLineVoltage(SystemContext)
|
|
.AddAverageLineToNeutralVoltage(SystemContext)
|
|
.AddAverageCurrent(SystemContext)
|
|
.AddTotalReactivePower(SystemContext)
|
|
.AddTotalApparentPower(SystemContext)
|
|
.AddAveragePowerFactor(SystemContext)
|
|
.AddTotalRealEnergy(SystemContext)
|
|
.AddLoadPercent(SystemContext)
|
|
.AddWindingTemperature1(SystemContext)
|
|
.AddConnection(SystemContext)
|
|
.AddExcitationType(SystemContext)
|
|
.AddNumberOfPoles(SystemContext);
|
|
|
|
foreach (AlternatorPhaseState phase in new[]
|
|
{
|
|
set.Alternator!.L1!, set.Alternator!.L2!, set.Alternator!.L3!,
|
|
})
|
|
{
|
|
phase.AddLineToNeutralVoltage(SystemContext)
|
|
.AddLineToLineVoltage(SystemContext)
|
|
.AddRealPower(SystemContext)
|
|
.AddReactivePower(SystemContext)
|
|
.AddApparentPower(SystemContext)
|
|
.AddPowerFactor(SystemContext);
|
|
}
|
|
|
|
set.FuelSystem!
|
|
.AddFuelLevel(SystemContext)
|
|
.AddFuelVolume(SystemContext)
|
|
.AddFuelConsumptionRate(SystemContext)
|
|
.AddRuntimeRemaining(SystemContext)
|
|
.AddTotalFuelConsumed(SystemContext);
|
|
|
|
set.CoolingSystem!
|
|
.AddCoolantTemperature(SystemContext)
|
|
.AddCoolantLevel(SystemContext)
|
|
.AddAmbientTemperature(SystemContext)
|
|
.AddCoolingMethod(SystemContext)
|
|
.AddRadiatorFanRunning(SystemContext);
|
|
|
|
set.LubricationSystem!
|
|
.AddOilPressure(SystemContext)
|
|
.AddOilTemperature(SystemContext)
|
|
.AddOilLevel(SystemContext);
|
|
|
|
set.StartingSystem!
|
|
.AddBatteryChargingCurrent(SystemContext)
|
|
.AddBatteryChargerActive(SystemContext)
|
|
.AddStartAttempts(SystemContext);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns the browse name for a one-based generator set number.
|
|
/// </summary>
|
|
/// <param name="setNumber">One-based unit number.</param>
|
|
/// <returns>The browse name.</returns>
|
|
internal static string GetGeneratorBrowseName(int setNumber)
|
|
{
|
|
return FormattableString.Invariant($"GeneratorSet_{setNumber}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns the display name for a one-based generator set number.
|
|
/// </summary>
|
|
/// <param name="setNumber">One-based unit number.</param>
|
|
/// <returns>The display name.</returns>
|
|
internal static string GetGeneratorDisplayName(int setNumber)
|
|
{
|
|
return FormattableString.Invariant($"Generator Set {setNumber}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns the datasheet serial number for a one-based generator set number.
|
|
/// </summary>
|
|
/// <param name="setNumber">One-based unit number.</param>
|
|
/// <returns>The serial number.</returns>
|
|
internal static string GetSerialNumber(int setNumber)
|
|
{
|
|
return FormattableString.Invariant($"SG-500-{setNumber:D3}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates the <see cref="GeneratorNodeManager"/> for the DI hosting pipeline.
|
|
/// </summary>
|
|
public sealed class GeneratorNodeManagerFactory : IAsyncNodeManagerFactory
|
|
{
|
|
private readonly IDiPostSetupRunner? m_postSetupRunner;
|
|
private readonly IOptions<GeneratorDeviceIntegrationOptions>? m_options;
|
|
|
|
/// <summary>
|
|
/// Initialises a factory without DI-hosting integration.
|
|
/// </summary>
|
|
public GeneratorNodeManagerFactory()
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// Initialises a factory that participates in the DI hosting pipeline.
|
|
/// </summary>
|
|
/// <param name="postSetupRunner">The DI post-setup pipeline.</param>
|
|
/// <param name="options">Sample options.</param>
|
|
public GeneratorNodeManagerFactory(
|
|
IDiPostSetupRunner? postSetupRunner,
|
|
IOptions<GeneratorDeviceIntegrationOptions>? options)
|
|
{
|
|
m_postSetupRunner = postSetupRunner;
|
|
m_options = options;
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public ArrayOf<string> NamespacesUris => new string[]
|
|
{
|
|
Opc.Ua.Generators.Namespaces.Generators,
|
|
Opc.Ua.Machinery.Namespaces.Machinery,
|
|
Opc.Ua.OpenUsd.Namespaces.OpenUSD,
|
|
}.ToArrayOf();
|
|
|
|
/// <inheritdoc/>
|
|
public ValueTask<IAsyncNodeManager> CreateAsync(
|
|
IServerInternal server,
|
|
ApplicationConfiguration configuration,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
#pragma warning disable CA2000 // ownership transferred to server
|
|
IAsyncNodeManager nodeManager =
|
|
new GeneratorNodeManager(server, configuration, m_postSetupRunner, m_options);
|
|
#pragma warning restore CA2000
|
|
return new ValueTask<IAsyncNodeManager>(nodeManager);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Source-generated log messages for <see cref="GeneratorNodeManager"/>.
|
|
/// </summary>
|
|
internal static partial class GeneratorNodeManagerLog {
|
|
[LoggerMessage(
|
|
EventId = GeneratorServerEventIds.GeneratorNodeManager + 0,
|
|
Level = LogLevel.Information,
|
|
Message = "Generator address space ready: {NodeCount} nodes, {SetCount} generator set(s).")]
|
|
public static partial void GeneratorAddressSpaceReady(
|
|
this ILogger logger, int nodeCount, int setCount);
|
|
|
|
[LoggerMessage(
|
|
EventId = GeneratorServerEventIds.GeneratorNodeManager + 1,
|
|
Level = LogLevel.Information,
|
|
Message = "Materialised generator set '{BrowseName}' as {NodeId}.")]
|
|
public static partial void MaterialisedGeneratorSet(
|
|
this ILogger logger, string? browseName, NodeId nodeId);
|
|
}
|
|
}
|