-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathPumpNodeManager.cs
More file actions
392 lines (358 loc) · 16.4 KB
/
Copy pathPumpNodeManager.cs
File metadata and controls
392 lines (358 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/* ========================================================================
* 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.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Di;
using Opc.Ua.Di.Server;
using Opc.Ua.Di.Server.Hosting;
using Opc.Ua.Machinery;
using Opc.Ua.Pumps;
using Opc.Ua.Server;
using Opc.Ua.Server.Fluent;
using Opc.Ua.Server.NodeManager;
namespace Pumps
{
/// <summary>
/// Hand-written node manager partial that provides the infrastructure
/// (constructor, address-space load, fluent builder wiring) for the
/// OPC 40223 Pumps companion specification server.
/// </summary>
public partial class PumpNodeManager : DiNodeManager
{
/// <summary>
/// Initialises a new <see cref="PumpNodeManager"/> without
/// DI-hosting integration.
/// </summary>
public PumpNodeManager(
IServerInternal server,
ApplicationConfiguration configuration)
: this(server, configuration, postSetupRunner: null)
{
}
/// <summary>
/// Initialises a new <see cref="PumpNodeManager"/> that
/// participates in the DI hosting post-setup pipeline.
/// </summary>
public PumpNodeManager(
IServerInternal server,
ApplicationConfiguration configuration,
IDiPostSetupRunner? postSetupRunner)
: base(
server,
configuration,
postSetupRunner,
Opc.Ua.Pumps.Namespaces.Pumps,
Opc.Ua.Machinery.Namespaces.Machinery)
{
// Base class constructor sets SystemContext.NodeIdFactory to
// itself; our New() override takes over.
SystemContext.NodeIdFactory = this;
}
/// <inheritdoc/>
public override NodeId New(ISystemContext context, NodeState node)
{
if (node is BaseInstanceState instance &&
instance.Parent != null)
{
string parentId = instance.Parent.NodeId.IdentifierAsString;
return new NodeId(
$"{parentId}_{instance.SymbolicName}",
instance.Parent.NodeId.NamespaceIndex);
}
return node.NodeId;
}
/// <inheritdoc/>
protected override ValueTask<NodeStateCollection> LoadPredefinedNodesAsync(
ISystemContext context,
CancellationToken cancellationToken = default)
{
// Compose the predefined-node tree from three source-generated
// models, in dependency order:
// - Opc.Ua.Di (referenced library)
// - Opc.Ua.Machinery (source-generated inside this assembly)
// - Opc.Ua.Pumps (source-generated inside this assembly)
// No runtime XML loading — the NodeSet2 XMLs ship only as
// <AdditionalFiles> for the source generator. The generated
// AddOpcUa* extension methods are idempotent and pull in
// their declared dependencies via [ModelDependencyAttribute],
// so a direct chain in dependency order is sufficient.
var nodes = new NodeStateCollection();
nodes.AddOpcUaDi(context);
nodes.AddOpcUaMachinery(context);
nodes.AddOpcUaPumps(context);
return new ValueTask<NodeStateCollection>(nodes);
}
/// <inheritdoc/>
protected override async ValueTask OnAddressSpaceReadyAsync(
CancellationToken cancellationToken)
{
// Configuration phase 1 (async): materialise the
// predefined instances that Configure(builder) will wire.
// Mirrors the synchronous fluent Configure(builder) but
// runs first so the builder has typed nodes available.
await ConfigureInstancesAsync(cancellationToken)
.ConfigureAwait(false);
// Configuration phase 2 (sync): wire fluent callbacks
// against the predefined nodes.
ushort nsIndex = (ushort)Server.NamespaceUris.GetIndex(
Opc.Ua.Pumps.Namespaces.Pumps);
CreateFluentBuilder(nsIndex)
.Configure(Configure)
.Seal();
m_logger.LogInformation(
"PumpNodeManager: address space ready ({NodeCount} predefined nodes).",
PredefinedNodes.Count);
// PostSetupRunner is invoked automatically by the base
// DiNodeManager.CreateAddressSpaceAsync after this method
// returns; no manual invocation needed here.
}
/// <summary>
/// Materialises the predefined instances that the fluent
/// <see cref="Configure"/> wiring expects to find. Runs as
/// the async phase of <see cref="OnAddressSpaceReadyAsync"/>
/// before the synchronous fluent builder pass.
/// </summary>
/// <remarks>
/// Cannot use
/// <see cref="DiNodeManager.CreateDeviceAsync{TDevice}(QualifiedName, NodeId, Func{NodeState, TDevice}, NodeState?, CancellationToken)"/>
/// here because <c>PumpType</c> in OPC 40223 derives from the
/// Machinery <c>MachineType</c>, not from the DI
/// <c>ComponentType</c> hierarchy that
/// <c>CreateDeviceAsync</c> requires
/// (<c>where TDevice : ComponentState</c>). The materialisation
/// therefore goes through
/// <see cref="MaterialisePumpInstanceAsync(QualifiedName, CancellationToken)"/>
/// which composes the same primitives
/// (<see cref="SystemContext"/> +
/// <see cref="CustomNodeManager2.AddPredefinedNodeAsync(ISystemContext, NodeState, CancellationToken)"/>)
/// directly.
/// </remarks>
private async ValueTask ConfigureInstancesAsync(
CancellationToken cancellationToken)
{
ushort pumpsNs = (ushort)Server.NamespaceUris
.GetIndex(Opc.Ua.Pumps.Namespaces.Pumps);
var pumpBrowseName = new QualifiedName("Pump #1", pumpsNs);
await MaterialisePumpInstanceAsync(pumpBrowseName, cancellationToken)
.ConfigureAwait(false);
}
/// <summary>
/// Creates a <see cref="PumpState"/> instance with the supplied
/// browse name as a child of the DI <c>DeviceSet</c> object and
/// registers it as a predefined node. The instance carries
/// <c>PumpType</c> as its TypeDefinitionId so clients see the
/// full OPC 40223 pump surface; the source-generated factory
/// materialises mandatory children (Identification) automatically.
/// Optional children that the fluent simulation wires
/// (Operational/Measurements/{analog states}, Events with the
/// SupervisionProcessFluid + SupervisionPumpOperation subtrees,
/// Maintenance) are materialised here via the generator-emitted
/// <c>AddXxx(context)</c> helpers; each new node gets a
/// per-instance NodeId via <see cref="AssignChildNodeIds"/>
/// before <c>AddPredefinedNodeAsync</c> recursively registers
/// the entire subtree.
/// </summary>
private async ValueTask MaterialisePumpInstanceAsync(
QualifiedName pumpBrowseName,
CancellationToken cancellationToken)
{
NodeState? deviceSet = PredefinedNodes.FindById(NodeId.Create(
Opc.Ua.Di.Objects.DeviceSet,
DiNamespaceUri,
Server.NamespaceUris));
if (deviceSet == null)
{
m_logger.LogWarning(
"DI DeviceSet not found — '{Name}' will not be created.",
pumpBrowseName.Name);
return;
}
// Fail-fast on duplicate.
if (deviceSet.FindChild(SystemContext, pumpBrowseName) != null)
{
m_logger.LogDebug(
"DeviceSet already contains '{Name}' — skipping recreation.",
pumpBrowseName.Name);
return;
}
PumpState pump = SystemContext
.CreateInstanceOfPumpType(deviceSet, pumpBrowseName);
pump.NodeId = SystemContext.NodeIdFactory.New(SystemContext, pump);
MaterialisePumpOptionalChildren(pump);
// AddChild defaults ReferenceTypeId to HasComponent when null
// (NodeState.AddChild line 4511-4514); ModellingRuleId defaults
// to NodeId.Null on every fresh NodeState — no explicit set needed.
deviceSet.AddChild(pump);
// Walk the whole pump subtree assigning per-instance NodeIds
// BEFORE AddPredefinedNodeAsync uses them as the PredefinedNodes
// dictionary key. The generator's AddXxx helpers stamp the
// TYPE NodeId on every new child; without this walk every
// instance of PumpType would collide on those NodeIds.
AssignChildNodeIds(pump);
await AddPredefinedNodeAsync(SystemContext, pump, cancellationToken)
.ConfigureAwait(false);
m_pump1 = pump;
m_logger.LogInformation(
"Materialised '{Name}' (PumpType) under DeviceSet, NodeId={NodeId}.",
pumpBrowseName.Name, pump.NodeId);
}
/// <summary>
/// Materialises the optional PumpType children that the fluent
/// simulation in <see cref="Configure"/> wires. Each call to a
/// generator-emitted <c>AddXxx(context)</c> helper creates the
/// child and assigns it to the parent's typed property; the
/// parent.AddChild bookkeeping happens inside the helpers
/// transparently.
/// </summary>
private void MaterialisePumpOptionalChildren(
PumpState pump)
{
pump.AddOperational(SystemContext);
OperationalGroupState operational = pump.Operational!;
operational.AddMeasurements(SystemContext);
MeasurementsState measurements = operational.Measurements!;
// Analog measurements wired by Configure.WithMeasurements.
measurements
.AddDifferentialPressure(SystemContext)
.AddFluidTemperature(SystemContext)
.AddBearingTemperature(SystemContext)
.AddPumpPowerInput(SystemContext)
.AddMassFlow(SystemContext)
.AddPumpEfficiency(SystemContext)
.AddLevel(SystemContext)
// Discrete count exposed via Configure.WithMaintenance.
.AddNumberOfStarts(SystemContext);
// Supervision subtree wired by Configure.WithSupervision —
// Cavitation under SupervisionProcessFluid, MotorOverheat
// under SupervisionPumpOperation.
pump.AddEvents(SystemContext);
SupervisionState events = pump.Events!;
events.AddSupervisionProcessFluid(SystemContext);
events.SupervisionProcessFluid!.AddCavitation(SystemContext);
events.AddSupervisionPumpOperation(SystemContext);
events.SupervisionPumpOperation!.AddMotorOverheat(SystemContext);
// Maintenance container — leaf wiring deferred until the
// typed-accessor generator (FB-3 phase 3) ships materialisable
// leaves for ConditionBasedMaintenance / BreakdownMaintenance.
pump.AddMaintenance(SystemContext);
}
/// <summary>
/// Recursively walks the children of <paramref name="parent"/>
/// and assigns per-instance NodeIds via the active
/// <see cref="ISystemContext.NodeIdFactory"/>. Required after
/// calling generator-emitted <c>AddXxx(context)</c> helpers
/// which stamp the TYPE NodeId on every new child.
/// </summary>
private void AssignChildNodeIds(NodeState parent)
{
var children = new List<BaseInstanceState>();
parent.GetChildren(SystemContext, children);
foreach (BaseInstanceState child in children)
{
child.NodeId = SystemContext.NodeIdFactory.New(
SystemContext, child);
AssignChildNodeIds(child);
}
}
/// <summary>
/// Registers a DI <c>DeviceHealth</c> variable that the
/// supervision simulation loop should toggle in response to
/// the simulated cavitation / motor-overheat flags. The
/// companion-spec PumpType does not itself expose
/// <c>DeviceHealth</c> (it inherits from
/// <see cref="TopologyElementState"/>, not
/// <see cref="DeviceState"/>); callers can
/// attach <c>DeviceHealth</c> to a sibling
/// <see cref="DeviceState"/> (e.g. the
/// declarative <c>Pump #2</c> created in <c>Program.cs</c>)
/// and register it here to participate in the simulation loop.
/// </summary>
/// <param name="health">
/// The variable to drive; pass <see langword="null"/> to detach.
/// </param>
public void RegisterSupervisedDeviceHealth(
BaseDataVariableState<DeviceHealthEnumeration>? health)
{
m_supervisedDeviceHealth = health;
}
/// <summary>
/// Partial wired by the Configure.cs sibling.
/// </summary>
partial void Configure(INodeManagerBuilder builder);
}
/// <summary>
/// Factory that produces <see cref="PumpNodeManager"/> instances.
/// When constructed by the DI container via
/// <c>AddNodeManager<PumpNodeManagerFactory>()</c>, the
/// post-setup runner is injected and forwarded to every manager
/// the factory produces, enabling
/// <c>ConfigureDevicesFor<PumpNodeManager>(...)</c>.
/// </summary>
public sealed class PumpNodeManagerFactory : IAsyncNodeManagerFactory
{
private readonly IDiPostSetupRunner? m_runner;
/// <summary>
/// Creates a factory without DI-hosting integration.
/// </summary>
public PumpNodeManagerFactory()
: this(null)
{
}
/// <summary>
/// Creates a factory that injects the post-setup runner into
/// every manager it produces.
/// </summary>
public PumpNodeManagerFactory(IDiPostSetupRunner? runner)
{
m_runner = runner;
}
/// <inheritdoc/>
public ArrayOf<string> NamespacesUris => new string[]
{
Opc.Ua.Pumps.Namespaces.Pumps,
Opc.Ua.Machinery.Namespaces.Machinery,
Opc.Ua.Di.Namespaces.OpcUaDi
};
/// <inheritdoc/>
public ValueTask<IAsyncNodeManager> CreateAsync(
IServerInternal server,
ApplicationConfiguration configuration,
CancellationToken cancellationToken = default)
{
#pragma warning disable CA2000 // ownership transferred to server
IAsyncNodeManager nm = new PumpNodeManager(server, configuration, m_runner);
#pragma warning restore CA2000
return new ValueTask<IAsyncNodeManager>(nm);
}
}
}