Files
UA-.NETStandard/samples/Machinery/MachineryServer/PressConfigurator.cs
Klaus LandsdorfandMarc Schier 01d6b5d26c Machinery: the OPC 40001 companion SDK with Jobs, Result Transfer, Process Values and Energy (#4578)
> Tracking issue #4576. #4577 is merged, so this branch is rebased onto
> `master` and contains only the Machinery commits.

## Summary

Second of four stacked PRs. Adds the OPC UA for Machinery series as
model
packages plus a server and a client SDK, following the companion pattern
of
DI and Robotics, and the two models it depends on that the repository
does
not carry yet.

| Package | Content |
|---|---|
| `Opc.Ua.IA` | OPC 10000-200 IA 1.01.4, **moved out of
`Opc.Ua.Robotics`** (see below) |
| `Opc.Ua.ECM` | OPC 34100 Energy Consumption Management 1.0.1 |
| `Opc.Ua.PADIM` | OPC 30081 PA-DIM 1.02.0 with the IRDI dictionary |
| `Opc.Ua.Machinery` | OPC 40001-1 Basic Building Blocks 1.04.1 |
| `Opc.Ua.Machinery.ProcessValues` | OPC 40001-2 Process Values 1.00.0 |
| `Opc.Ua.Machinery.Jobs` | OPC 40001-3 Job Management 1.0.1 |
| `Opc.Ua.Machinery.Energy` | OPC 40001-4 Energy 1.00 |
| `Opc.Ua.Machinery.Result` | OPC 40001-101 Result Transfer 1.01.0 |
| `Opc.Ua.Machinery.Server` | `AddMachinery()` /
`ConfigureMachinery(...)`, fluent machine builder, server-driven state
machines, process values, job management over the shared ISA-95 V2
binder, energy, result management incl. `GenerateFileForRead` |
| `Opc.Ua.Machinery.Client` | machine discovery, identification, state
observation, process values, job and result access |

OPC 40001-101 `ResultTransferType` redeclares `GenerateFileForRead` with
its
own arguments; the generator fix for such overrides, merged with #4577,
is
what makes it appear on the `ResultTransfer` instances.

All NodeSets are byte-identical to `UA-Nodeset/latest`. Each model
carries a
pinned `Model/*.NodeIds.csv` the generator validates, next to the
unmodified
upstream table; `tools/nodesets/derive-identifier-table.py` derives the
former from the latter.

## Changes to existing code

- **IA moves out of Robotics.** Machinery needs IA as well (OPC 40001-1
types
`Stacklight` with `BasicStacklightType`), and two assemblies generating
the
same model under the same prefix collide at any consumer referencing
both.
The NodeSet moves verbatim, so no generated type changes; the prefix
stays
`Opc.Ua.IA`. Source-compatible, but IA types now live in `Opc.Ua.IA.dll`
rather than `Opc.Ua.Robotics.dll` — binary-breaking for consumers of the
  Robotics package.
- **`samples/OpenUsd/GeneratorServer`** drops its hand-reduced Machinery
  NodeSet copy and the script that produced it (a workaround for the
generator defect fixed by #4577) and references `Opc.Ua.Machinery`
instead.
- `README.md` and `docs/README.md` list the new models; the README also
  corrects the Industrial Automation entry (Part 200, not OPC 40001-1).

## Review follow-ups

Separate commits after the docs/samples commit, so the reviewed state
stays
comparable. Each fix comes with a test that fails without it.

- Copilot review: a transition is committed only while the state machine
is
still in its source state; optional Jobs/Result namespaces the server
does
not load are reported as absent, as documented; resources of registered
machines (result transfer, job-management change pumps) are released
with
  the node manager (`DisposeMachineryResourcesAsync` for a custom DI
  manager); `NodeId`/`LocalizedText` use their null sentinels instead of
  `Nullable<T>`.
- Own review with the rubric in `.github/copilot-instructions.md`: a
failed
browse call propagates from the client instead of reading as "no
children";
  the predefined result metadata compares `CreationTime` against the
  `DateTimeUtc` sentinels (the `DateTime` conversion shifted
  `DateTime.MaxValue` by the host's UTC offset); process values below
`Monitoring` are found; a second metering point named `Main` is
rejected;
  the zero-point event is reported when the handler throws; smaller
  state-sharing and documentation corrections.

## Testing

- `tests/Opc.Ua.Machinery.Tests`: 162 tests on net8 and net10 and with
the
netstandard2.1 libraries; the integration tests connect a real client
session over `opc.tcp` to a hosted
  server.
- With IA extracted: Robotics 636, OpenUsd 921, DI 433 and
SourceGeneration
  263 tests pass.
- `UA.slnx` builds for net472, net48, netstandard2.0/2.1 and net8/9/10
with
  SDK 10.0.401 and no warnings.
- Changed-line coverage of this layer (`check-coverage.ps1`): 91.68 %
(6059 of 6609 changed lines, against `master`).
- Fork CI, full PR matrix incl. macOS, on the current master: green, all
184
jobs ([run
36582685653](https://github.com/biancode/UA-.NETStandard/actions/runs/36582685653)).
CodeQL: green ([run
36582689589](https://github.com/biancode/UA-.NETStandard/actions/runs/36582689589)).
- Beyond the in-repo tests the implementation has been validated end to
end
  against a separate, non-public OPC UA client and server.

## Reviewing

Commits are ordered so each builds: IA extraction → identifier-table
tool →
ECM/PA-DIM → Machinery models → server → client → tests → docs/samples →
GeneratorServer sample → review follow-ups. The model commits are large
only because of the
NodeSets and identifier tables; the hand-written code starts at the
server
commit.

---------

Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
2026-09-29 19:59:34 +02:00

278 lines
14 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Threading;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Di;
using Opc.Ua.ISA95.Server.Providers;
using Opc.Ua.Machinery.Server;
using Opc.Ua.Machinery.Server.Builders;
using Opc.Ua.Machinery.Server.Results;
using Opc.Ua.Machinery.Server.StateMachines;
namespace MachinerySample
{
/// <summary>
/// Builds the sample machine. Every OPC 40001 part appears exactly once, so
/// the file doubles as a worked example of the fluent builder surface.
/// </summary>
internal sealed class PressConfigurator : IMachineryConfigurator
{
public PressConfigurator(PressSimulation simulation)
{
m_simulation = simulation ?? throw new ArgumentNullException(nameof(simulation));
}
public async ValueTask ConfigureAsync(
IMachineryBuildContext context,
CancellationToken cancellationToken)
{
IMachineHandle<BaseObjectState> press = await context
.AddMachine(new QualifiedName("HydraPress-1"))
// OPC 40001-1: the identification add-in. Manufacturer and
// SerialNumber are mandatory on every machinery item, and a
// machine adds ProductInstanceUri on top.
.WithIdentification(id =>
{
id.Manufacturer = new LocalizedText(PressDatasheet.Manufacturer);
id.ManufacturerUri = PressDatasheet.ManufacturerUri;
id.Model = new LocalizedText(PressDatasheet.Model);
id.ProductCode = PressDatasheet.ProductCode;
id.SerialNumber = PressDatasheet.SerialNumber;
id.ProductInstanceUri = PressDatasheet.ProductInstanceUri;
id.DeviceClass = PressDatasheet.DeviceClass;
id.HardwareRevision = PressDatasheet.HardwareRevision;
id.SoftwareRevision = PressDatasheet.SoftwareRevision;
id.Location = PressDatasheet.Location;
id.YearOfConstruction = PressDatasheet.YearOfConstruction;
id.MonthOfConstruction = PressDatasheet.MonthOfConstruction;
})
// OPC 40001-1: the monitoring add-in. Neither state machine
// declares a cause method, so both are driven from the
// simulation below and never by a client.
.WithMonitoring(monitoring => monitoring
.WithMachineryItemState(MachineryItemStateValue.NotExecuting)
.WithOperationMode(MachineryOperationModeValue.None)
.WithHealth(health => health
.WithDeviceHealth(DeviceHealthEnumeration.NORMAL))
.WithProcess())
.WithComponents(components => components
.AddComponent(
new QualifiedName("HydraulicUnit"),
component => component
.WithIdentification(id =>
{
id.Manufacturer =
new LocalizedText(PressDatasheet.Manufacturer);
id.SerialNumber = "HU-2024-0114";
id.Model = new LocalizedText("HydraPack 250");
id.DeviceRevision = "B";
})
.WithLifetimeCounters(counters => counters.AddLifetimeVariable(
new QualifiedName("SealLife"),
PressDatasheet.SealLifetimeCycles,
PressDatasheet.SealRemainingCycles,
new[] { PressDatasheet.SealWarningCycles }.ToArrayOf()))))
.WithMachineryEquipment(equipment => equipment.AddEquipment(
new QualifiedName("UpperDie"),
"urn:acme-machine-tools.example:equipment:die",
die => die
.WithDescription(new LocalizedText("Upper forming die, 300 x 200 mm"))
.WithIdentification(id =>
{
id.Manufacturer = new LocalizedText("Acme Tooling");
id.SerialNumber = "DIE-77120";
})
// EquipmentLife comes from IMachineryEquipmentType, an
// interface, so the placeholder factory never creates
// it; the builder does.
.WithEquipmentLife(
remaining: PressDatasheet.DieRemainingCycles,
startValue: PressDatasheet.DieLifetimeCycles,
warningValues:
new[] { PressDatasheet.DieWarningCycles }.ToArrayOf())))
// The Notifications add-in is where a machine puts its own
// events. The publisher is what the simulation reports the
// stroke event on.
.WithNotifications(notifications =>
notifications.Bind(out m_notifications))
.WithOperationCounters(counters => counters
.WithPowerOnDuration(PressDatasheet.PowerOnDurationHours)
.WithOperationDuration(PressDatasheet.OperationDurationHours))
// OPC 40001-2: a process value over the PADIM analog-signal
// model, with the limits and the alarms the part adds.
.WithProcessValue(
new QualifiedName("HydraulicOilTemperature"),
processValue => processValue
.WithEngineeringUnits(
DegreeCelsius(),
new Opc.Ua.Range
{
Low = PressDatasheet.OilTemperatureRangeLow,
High = PressDatasheet.OilTemperatureRangeHigh
})
.WithLimits(
lowLow: PressDatasheet.OilTemperatureLowLowLimit,
low: PressDatasheet.OilTemperatureLowLimit,
high: PressDatasheet.OilTemperatureHighLimit,
highHigh: PressDatasheet.OilTemperatureHighHighLimit)
.WithSetpoint(PressDatasheet.OilTemperatureSetpoint)
.WithDeviationLimits(
lowLow: -20,
low: -10,
high: 10,
highHigh: 20,
autoAdjustment: false,
sensitivity: 5)
.WithPercentageValue()
.WithStatus()
// Both alarms take their limits from the two calls
// above and follow every SetValueAsync from here on.
.WithLimitAlarm()
.WithDeviationAlarm()
// OPC 40001-2 requires every instance publishing the
// method to report the event, which the builder does;
// the handler only says how it went.
.WithZeroPointAdjustment((_, _) =>
new ValueTask<StatusCode>(StatusCodes.Good))
.WithValue(PressDatasheet.OilTemperatureSetpoint)
.Bind(out m_oilTemperature))
// OPC 40001-3: job management. The eleven job verbs come from
// the ISA-95 Job Control V2 model underneath, bound to the
// in-memory provider this sample registers.
.WithJobManagement(jobs => jobs
.WithJobOrderReceiver(m_simulation.JobProvider)
.WithJobResponseProvider(m_simulation.JobProvider)
.WithJobOrderCatalog(m_simulation.JobProvider))
// OPC 40001-4: the compressed-air supply, tied to the
// well-known carrier with the Energy model's Contains
// reference.
// OPC 40001-4: the resources sit below Monitoring/Consumption,
// each with a Main metering point of the OPC 34100
// EnergyMeasurementType. WithEnergy materialises the monitoring
// add-in and the Consumption folder if they are not there yet.
.WithEnergy(energy => energy
.AddResource(MachineryEnergyCarrier.CompressedAir, air =>
{
air.Main
.WithApplicationTag("HydraPress-1/CompressedAir")
.WithNonElectricalEnergy(
importHighPrecision: 0,
exportHighPrecision: 0)
.WithVolumeFlow(
PressDatasheet.CompressedAirVolume,
PressDatasheet.CompressedAirVolumeFlowRate)
.WithBaseFlow(
PressDatasheet.CompressedAirPressurePascal,
PressDatasheet.CompressedAirTemperatureKelvin);
// A sub-meter whose consumption is part of Main's, which
// is exactly what the Contains reference states.
air.AddMeteringPoint(
new QualifiedName("ClampingCylinders"),
point => point
.WithApplicationTag("HydraPress-1/CompressedAir/Clamping")
.WithNonElectricalEnergy(
importHighPrecision: 0,
exportHighPrecision: 0));
})
// Electricity is the one resource OPC 40001-4 does not
// describe with interfaces of its own — it defers to
// OPC 34100's energy profiles, so the metering point takes
// one of those.
.AddResource(MachineryEnergyCarrier.Electricity, electricity =>
electricity.Main
.WithApplicationTag("HydraPress-1/Electricity")
.WithInterface(NodeId.Create(
Opc.Ua.ECM.ObjectTypes.IEnergyProfileE1Type,
Opc.Ua.ECM.Namespaces.ECM,
context.Context.NamespaceUris))
.AddMeasurementValue(
new QualifiedName(Opc.Ua.ECM.BrowseNames.AcActivePowerTotal),
Variant.From(PressDatasheet.ElectricalActivePowerTotal),
Watt())))
// OPC 40001-101: results, including the GenerateFileForRead
// download path.
.WithResultManagement(results => results
.WithInMemoryStore(capacity: 32)
.WithResultsFolder(publishedResults: 4)
.WithFileTransfer())
.BuildAsync(cancellationToken)
.ConfigureAwait(false);
m_simulation.Attach(press, m_oilTemperature!, m_notifications!);
}
private static EUInformation Watt()
{
// UNECE Recommendation 20 code for watt.
return new EUInformation
{
NamespaceUri = "http://www.opcfoundation.org/UA/units/un/cefact",
UnitId = 5720150,
DisplayName = new LocalizedText("W"),
Description = new LocalizedText("watt")
};
}
private static EUInformation DegreeCelsius()
{
// UNECE Recommendation 20 code for degree Celsius.
return new EUInformation
{
NamespaceUri = "http://www.opcfoundation.org/UA/units/un/cefact",
UnitId = 4408652,
DisplayName = new LocalizedText("°C"),
Description = new LocalizedText("degree Celsius")
};
}
private readonly PressSimulation m_simulation;
private IProcessValueHandle? m_oilTemperature;
private IMachineryNotificationPublisher? m_notifications;
}
}