mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-18 22:55:08 +08:00
4756e7c245
This PR implements the **OPC UA Device Integration (DI, OPC 10000-100)** companion-spec library trio (`Opc.Ua.Di` / `Opc.Ua.Di.Server` / `Opc.Ua.Di.Client`) plus a worked example (`Applications/MinimalPumpServer`) demonstrating the OPC 40223 Pumps companion specification end-to-end with full simulation. It also closes 11 fluent-API gaps in `Opc.Ua.Server.Fluent`, three source-generator bugs, integrates the DI layer into the unified `services.AddOpcUa()` Microsoft.Extensions DI hosting pattern, and adds 250+ new tests. **Worked example — `Applications/MinimalPumpServer/`** - AOT-compatible console host using `Host.CreateApplicationBuilder` + `AddOpcUa()`. - `PumpNodeManager` inherits from `DiNodeManager`; multi-namespace (DI + Machinery + Pumps) via runtime NodeSet2 loading and `ModelLoaderBuilder`. - Demonstrates declarative second-pump creation via `.ConfigureDevicesFor<PumpNodeManager>(...)` and software-package seeding from the same configurator. - Full simulation: pressure, temperatures, power, flow, efficiency, level, cavitation/overheat fault injection, alarm setup, NAMUR-style supervision. **Documentation** - `Docs/Opc.Ua.Di/` — README, DeviceBuilder, Hosting, LockService, SoftwareUpdate, ClientHelpers (6 new developer guides). - `Docs/Opc.Ua.Di/ComplianceMatrix.md` — every DI declaration mapped to In-v1 / Generated / Deferred / Excluded. - `Docs/CompanionSpecLibraries.md` — packaging guide for new companion-spec libraries. - `Docs/FluentApiGaps.md` — historical record of G1–G11. - `Docs/SourceGeneratedNodeManagers.md` updated for richer node managers. - `Docs/plans/StateMachineBuilder.md` — deferred state-machine builder design.
236 lines
9.8 KiB
C#
236 lines
9.8 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.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Xml.Linq;
|
|
using BenchmarkDotNet.Attributes;
|
|
using Microsoft.CodeAnalysis;
|
|
using Microsoft.CodeAnalysis.CSharp;
|
|
using Microsoft.CodeAnalysis.Diagnostics;
|
|
using Microsoft.Extensions.Logging;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Tests;
|
|
|
|
namespace Opc.Ua.SourceGeneration.Api.Tests
|
|
{
|
|
/// <summary>
|
|
/// Test generating and compiling stack
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Category("Api")]
|
|
[SetCulture("en-us")]
|
|
[SetUICulture("en-us")]
|
|
[MemoryDiagnoser]
|
|
[DisassemblyDiagnoser]
|
|
// [Parallelizable(ParallelScope.All)]
|
|
public class GenerateStackTests
|
|
{
|
|
[DatapointSource]
|
|
public OptimizationLevel[] OptimizationLevels = CompilerUtils.SupportedOptimizationLevels;
|
|
|
|
[DatapointSource]
|
|
public StackGenerationType[] GenerationTypes =
|
|
[
|
|
StackGenerationType.None,
|
|
StackGenerationType.Stack,
|
|
StackGenerationType.Models,
|
|
StackGenerationType.All
|
|
];
|
|
|
|
[Theory]
|
|
public void GenerateStackTest(StackGenerationType generationType)
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create(logLevel: LogLevel.Error);
|
|
GenerateStack(generationType, telemetry, out _);
|
|
}
|
|
|
|
[Theory]
|
|
public async Task GenerateAndCompileStackTestAsync(
|
|
OptimizationLevel optimizationLevel,
|
|
bool withAnalyzers,
|
|
bool withNodeLoader)
|
|
{
|
|
// Generate
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create(logLevel: LogLevel.Error);
|
|
Dictionary<string, string> generatedText = GenerateStack(StackGenerationType.All, telemetry, out _);
|
|
if (withNodeLoader)
|
|
{
|
|
AddPredefinedNodeLoader(generatedText);
|
|
}
|
|
|
|
// Parse and compile the generated code
|
|
var sw = Stopwatch.StartNew();
|
|
using var peStream = new MemoryStream();
|
|
using var xmlStream = new MemoryStream();
|
|
bool success = optimizationLevel
|
|
.CreateCompilation()
|
|
.AddCode(generatedText.WithOpcUaCoreStubs(), LanguageVersion.Latest) // Only support latest - internal use only
|
|
.WithAnalyzers(withAnalyzers, out CompilationWithAnalyzers compilationWithAnalyzers)
|
|
.Emit(peStream, xmlDocumentationStream: xmlStream)
|
|
.Check(TestContext.Out, out int errorCount, out int warnCount);
|
|
TestContext.Out.WriteLine("Compilation completed in {0} ms", sw.ElapsedMilliseconds);
|
|
if (withAnalyzers)
|
|
{
|
|
if (compilationWithAnalyzers == null)
|
|
{
|
|
Assert.Ignore("Setup does not support analyzer testing");
|
|
}
|
|
AnalysisResult analysisResults =
|
|
await compilationWithAnalyzers.GetAnalysisResultAsync(default).ConfigureAwait(false);
|
|
analysisResults.GetAllDiagnostics().Check(TestContext.Out,
|
|
out int analyzerErrors,
|
|
out int analzyerWarnings);
|
|
Assert.That(analyzerErrors, Is.Zero, $"Analyzers produced {analyzerErrors} errors");
|
|
TestContext.Out.WriteLine($"Analyzers produced {analzyerWarnings} warnings");
|
|
}
|
|
Assert.That(
|
|
success,
|
|
Is.True,
|
|
$"Compilation failed with {errorCount} errors and {warnCount} warnings.");
|
|
xmlStream.Position = 0;
|
|
var xmlDoc = XDocument.Load(xmlStream);
|
|
Assert.That(xmlDoc, Is.Not.Null);
|
|
}
|
|
|
|
[GlobalSetup(Target = nameof(GenerateToFile))]
|
|
[GlobalCleanup(Target = nameof(GenerateToFile))]
|
|
#pragma warning disable NUnit1028 // The non-test method is public
|
|
public void Setup()
|
|
#pragma warning restore NUnit1028 // The non-test method is public
|
|
{
|
|
try
|
|
{
|
|
Directory.Delete(Path.Combine(Directory.GetCurrentDirectory(), "Benchmark"), true);
|
|
}
|
|
catch
|
|
{
|
|
// Ignore
|
|
}
|
|
}
|
|
|
|
[Benchmark]
|
|
#pragma warning disable NUnit1028 // The non-test method is public
|
|
public void GenerateToFile()
|
|
#pragma warning restore NUnit1028 // The non-test method is public
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.CreateForBenchmarks(logLevel: LogLevel.Error);
|
|
Generators.GenerateStack(
|
|
StackGenerationType.All,
|
|
LocalFileSystem.Instance,
|
|
Path.Combine(Directory.GetCurrentDirectory(), "Benchmark"), telemetry);
|
|
}
|
|
|
|
[Benchmark]
|
|
#pragma warning disable NUnit1028 // The non-test method is public
|
|
public void GenerateToMemory()
|
|
#pragma warning restore NUnit1028 // The non-test method is public
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.CreateForBenchmarks(logLevel: LogLevel.Error);
|
|
GenerateStack(StackGenerationType.All, telemetry, out _);
|
|
}
|
|
|
|
[Benchmark]
|
|
[Arguments(OptimizationLevel.Release)]
|
|
[Arguments(OptimizationLevel.Debug)]
|
|
#pragma warning disable NUnit1028 // The non-test method is public
|
|
public void GenerateAndComile(OptimizationLevel optimizationLevel)
|
|
#pragma warning restore NUnit1028 // The non-test method is public
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.CreateForBenchmarks(logLevel: LogLevel.Error);
|
|
Dictionary<string, string> generatedText = GenerateStack(StackGenerationType.All, telemetry, out _);
|
|
using var peStream = new MemoryStream();
|
|
using var xmlStream = new MemoryStream();
|
|
bool success = optimizationLevel
|
|
.CreateCompilation("Opc.Ua.Test")
|
|
.AddCode(generatedText.WithOpcUaCoreStubs(), LanguageVersion.Latest)
|
|
.Emit(peStream, xmlDocumentationStream: xmlStream)
|
|
.Check(TestContext.Out, out int errorCount, out int warnCount);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Generate stack code
|
|
/// </summary>
|
|
#pragma warning disable NUnit1028 // The non-test method is public
|
|
internal static Dictionary<string, string> GenerateStack(
|
|
#pragma warning restore NUnit1028 // The non-test method is public
|
|
StackGenerationType generationType,
|
|
ITelemetryContext telemetry,
|
|
out Dictionary<string, string> nonSourceCode)
|
|
{
|
|
// Generate
|
|
var sw = Stopwatch.StartNew();
|
|
using var fileSystem = new VirtualFileSystem();
|
|
// The test compilation provides Core stubs via
|
|
// WithOpcUaCoreStubs() but no Opc.Ua.Server reference.
|
|
// Suppress fluent-builder emission to keep the generated
|
|
// code self-contained (mirrors model-only csproj
|
|
// configuration in production).
|
|
Generators.GenerateStack(generationType, fileSystem, string.Empty, telemetry,
|
|
new GeneratorOptions
|
|
{
|
|
OmitFluentApi = true
|
|
});
|
|
var generatedText = fileSystem.CreatedFiles
|
|
.Where(c => Path.GetExtension(c) == ".cs")
|
|
.ToDictionary(c => c, c => Encoding.UTF8.GetString(fileSystem.Get(c)));
|
|
|
|
TestContext.Out.WriteLine("Generation completed in {0} ms", sw.ElapsedMilliseconds);
|
|
Assert.That(generatedText.Values, Is.All.StartsWith("// <auto-generated />"));
|
|
|
|
nonSourceCode = fileSystem.CreatedFiles
|
|
.Where(c => Path.GetExtension(c) != ".cs")
|
|
.ToDictionary(c => c, c => Encoding.UTF8.GetString(fileSystem.Get(c)));
|
|
return generatedText;
|
|
}
|
|
|
|
private static void AddPredefinedNodeLoader(Dictionary<string, string> generated)
|
|
{
|
|
generated.Add("Test.cs",
|
|
"""
|
|
namespace Opc.Ua
|
|
{
|
|
public static partial class LoadingTestData
|
|
{
|
|
public static NodeStateCollection Load()
|
|
{
|
|
// Use predefined nodes
|
|
return new NodeStateCollection().AddOpcUa(new SystemContext(null));
|
|
}
|
|
}
|
|
}
|
|
""");
|
|
}
|
|
}
|
|
}
|