mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-18 22:55:08 +08:00
01d6b5d26c
> 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>
258 lines
10 KiB
C#
258 lines
10 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.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using Opc.Ua;
|
|
using Opc.Ua.ISA95.Server.Providers;
|
|
using Opc.Ua.Machinery.Result;
|
|
using Opc.Ua.Machinery.Server.Builders;
|
|
using Opc.Ua.Machinery.Server.Results;
|
|
using Opc.Ua.Machinery.Server.StateMachines;
|
|
|
|
namespace MachinerySample
|
|
{
|
|
/// <summary>
|
|
/// Runs the press. One stroke every
|
|
/// <see cref="PressDatasheet.CycleSeconds"/> seconds: the item state moves
|
|
/// to <c>Executing</c>, the operation mode to <c>Processing</c>, and each
|
|
/// finished stroke publishes an OPC 40001-101 result whose payload a client
|
|
/// can download.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// OPC 40001-1 declares no cause method on either state machine, so state
|
|
/// only ever moves from here. A client observes it; it cannot request it.
|
|
/// </remarks>
|
|
internal sealed class PressSimulation : BackgroundService
|
|
{
|
|
public PressSimulation(ILogger<PressSimulation> logger)
|
|
{
|
|
m_logger = logger;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The ISA-95 Job Control V2 provider the OPC 40001-3 job verbs are
|
|
/// bound to.
|
|
/// </summary>
|
|
public InMemoryIsa95JobControlProvider JobProvider { get; } = new();
|
|
|
|
public void Attach(
|
|
IMachineHandle<BaseObjectState> press,
|
|
IProcessValueHandle oilTemperature,
|
|
IMachineryNotificationPublisher notifications)
|
|
{
|
|
m_press = press ?? throw new ArgumentNullException(nameof(press));
|
|
m_oilTemperature = oilTemperature ??
|
|
throw new ArgumentNullException(nameof(oilTemperature));
|
|
m_notifications = notifications ??
|
|
throw new ArgumentNullException(nameof(notifications));
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
TimeSpan cycle = TimeSpan.FromSeconds(PressDatasheet.CycleSeconds);
|
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
try
|
|
{
|
|
await Task.Delay(cycle, stoppingToken).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
return;
|
|
}
|
|
|
|
IMachineHandle<BaseObjectState>? press = m_press;
|
|
if (press == null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
try
|
|
{
|
|
await RunStrokeAsync(press, stoppingToken).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
|
{
|
|
return;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
m_logger.PressStrokeFailed(ex);
|
|
}
|
|
}
|
|
}
|
|
|
|
private async ValueTask RunStrokeAsync(
|
|
IMachineHandle<BaseObjectState> press,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
m_cycle++;
|
|
|
|
if (press.OperationMode != null)
|
|
{
|
|
await press.OperationMode
|
|
.SetModeAsync(MachineryOperationModeValue.Processing, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
}
|
|
if (press.ItemState != null)
|
|
{
|
|
await press.ItemState
|
|
.SetStateAsync(MachineryItemStateValue.Executing, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
}
|
|
|
|
await Task.Delay(
|
|
TimeSpan.FromSeconds(PressDatasheet.CycleSeconds / 2),
|
|
cancellationToken)
|
|
.ConfigureAwait(false);
|
|
|
|
if (press.ItemState != null)
|
|
{
|
|
await press.ItemState
|
|
.SetStateAsync(MachineryItemStateValue.NotExecuting, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
}
|
|
|
|
// The oil warms while pressing and cools between strokes. Writing
|
|
// it through the handle is what drives the percentage value and
|
|
// both alarms — crossing a limit reports an alarm event without
|
|
// the simulation having to know the alarm exists.
|
|
await m_oilTemperature!
|
|
.SetValueAsync(OilTemperature(m_cycle), cancellationToken)
|
|
.ConfigureAwait(false);
|
|
|
|
if (press.Results != null)
|
|
{
|
|
await press.Results
|
|
.PublishAsync(CreateResult(m_cycle), cancellationToken)
|
|
.ConfigureAwait(false);
|
|
}
|
|
|
|
await PublishStrokeNotificationAsync(cancellationToken).ConfigureAwait(false);
|
|
m_logger.PressStrokeCompleted(m_cycle);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reports a stroke event on the machine's OPC 40001-1
|
|
/// <c>Notifications</c> add-in.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// OPC 40001-1 says where a machine publishes its events but not what
|
|
/// they are, so the sample uses the stock <c>SystemEventType</c> —
|
|
/// concrete, and therefore something a client can filter for.
|
|
/// </remarks>
|
|
private ValueTask PublishStrokeNotificationAsync(CancellationToken cancellationToken)
|
|
{
|
|
IMachineryNotificationPublisher notifications = m_notifications!;
|
|
ISystemContext context = notifications.Context;
|
|
var notification = new SystemEventState(null);
|
|
notification.Initialize(
|
|
context,
|
|
notifications.Notifier,
|
|
EventSeverity.Low,
|
|
new LocalizedText(
|
|
FormattableString.Invariant($"Press stroke {m_cycle} completed.")));
|
|
notification.TypeDefinitionId = Opc.Ua.ObjectTypeIds.SystemEventType;
|
|
notification.EventType!.Value = Opc.Ua.ObjectTypeIds.SystemEventType;
|
|
return notifications.PublishAsync(notification, cancellationToken);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A slow triangular ramp that walks the oil temperature across the
|
|
/// datasheet's high limit every few dozen strokes, so a client
|
|
/// watching the press sees the limit alarm activate and clear.
|
|
/// </summary>
|
|
private static double OilTemperature(long cycle)
|
|
{
|
|
const double amplitude =
|
|
PressDatasheet.OilTemperatureHighHighLimit -
|
|
PressDatasheet.OilTemperatureSetpoint + 5.0;
|
|
return PressDatasheet.OilTemperatureSetpoint +
|
|
(amplitude * Math.Sin(cycle / 6.0));
|
|
}
|
|
|
|
private static MachineryResult CreateResult(long cycle)
|
|
{
|
|
string resultId = FormattableString.Invariant($"stroke-{cycle:D6}");
|
|
double peakForce = PressDatasheet.NominalForceKiloNewton *
|
|
(0.92 + (0.05 * Math.Sin(cycle / 7.0)));
|
|
|
|
var metaData = new ResultMetaDataType
|
|
{
|
|
ResultId = resultId,
|
|
CreationTime = DateTimeUtc.Now,
|
|
ResultEvaluation = ResultEvaluationEnum.OK,
|
|
EncodingMask = (uint)(
|
|
ResultMetaDataTypeFields.CreationTime |
|
|
ResultMetaDataTypeFields.ResultEvaluation)
|
|
};
|
|
|
|
var data = new ResultDataType
|
|
{
|
|
ResultMetaData = metaData,
|
|
ResultContent = new[] { Variant.From(peakForce) }.ToArrayOf()
|
|
};
|
|
|
|
string payload = FormattableString.Invariant(
|
|
$"resultId,{resultId}\npeakForceKN,{peakForce:F1}\n");
|
|
return new MachineryResult(
|
|
data,
|
|
new ByteString(Encoding.UTF8.GetBytes(payload)),
|
|
"text/csv");
|
|
}
|
|
|
|
private readonly ILogger<PressSimulation> m_logger;
|
|
private IMachineHandle<BaseObjectState>? m_press;
|
|
private IProcessValueHandle? m_oilTemperature;
|
|
private IMachineryNotificationPublisher? m_notifications;
|
|
private long m_cycle;
|
|
}
|
|
|
|
internal static partial class PressSimulationLog
|
|
{
|
|
[LoggerMessage(
|
|
EventId = 1,
|
|
Level = LogLevel.Information,
|
|
Message = "Press stroke {Cycle} completed; result published.")]
|
|
public static partial void PressStrokeCompleted(this ILogger logger, long cycle);
|
|
|
|
[LoggerMessage(
|
|
EventId = 2,
|
|
Level = LogLevel.Error,
|
|
Message = "A press stroke failed.")]
|
|
public static partial void PressStrokeFailed(this ILogger logger, Exception exception);
|
|
}
|
|
}
|