Files
UA-.NETStandard/tests/Opc.Ua.Vision.Tests/MachineVisionRuntimeTests.Integration.cs
Marc Schier 1bb4bdca1d Add Machine Vision Parts 1 and 2 (#4733)
# Description

Implement the released [OPC
40100-1](https://reference.opcfoundation.org/specs/OPC-40100-1) and [OPC
40100-2](https://reference.opcfoundation.org/specs/OPC-40100-2)
specifications with generated models, provider-backed runtimes, typed
clients, MCP workflows, and DI/Machinery integration.

- **Part 1 stays in `Opc.Ua.Vision`** and its client/server packages
alongside the distinct Perception model. Provide control/acquisition
state machines, jobs and synchronized steps,
recipe/product/configuration/result management, file transfers,
diagnostics, events, and conditions.
- **Part 2 is in `Opc.Ua.MachineVision`, `.Client`, and `.Server`.**
Provide asset categories, identification, image-handling aspects,
health/maintenance data, topology, and transactional updates. The base
Vision assemblies do not reference these optional packages; the Part 2
wire model does not depend on Part 1.
- Preserve the release-pinned model bytes, wire namespaces and NodeIds.
Perception types are in `Opc.Ua.Vision.Perception`; the AMCM generated
namespace remains `Opc.Ua.Vision.MachineVision.AMCM`, and asset
client/server extension namespaces remain `Opc.Ua.Vision.Client` and
`Opc.Ua.Vision.Server`.
- Use `AddOpcUaMachineVision` and `AddOpcUaMachineVisionAMCM` for model
loading and factory registration. Each has node-collection,
encodeable-factory-builder and node-state-factory-builder overloads.
These short entry points delegate to the generated implementations;
existing namespace-derived generated names remain available for
compatibility.
- Support multiple independent named systems/assets under one
namespace-owning manager. Reuse injectable providers, file binding,
bounded memory stores, optional transactional `IFileSystemProvider`
persistence, state machines, telemetry and conformance infrastructure.
- Keep one `docs/Vision.md` guide, titled `Machine Vision (OPC 40100-1
and OPC 40100-2)`, and one `Opc.Ua.Mcp.Vision` package. Include
deterministic server/client samples.
- Expose 17 Machine Vision MCP tools, including capabilities/status,
bounded relationships and observation, complete small-file
uploads/downloads, management, explicit control, conditions, and chunked
transfers. Catalogue counts: 39 Vision-specific, 43 with connection
tools, 81 Vision+Robotics, 155 Full. Every Machine Vision wire parameter
has a schema description.

**Compatibility and limits:** `AddVision()` remains Perception-only
unless released parts are selected. Standalone Part 2 uses
`AddVision().AddMachineVision()`; Machinery composition uses
`AddVisionToMachinery()`. Existing tool defaults and command signatures
are preserved. Observation owns and cleans up its subscription: 5
seconds/50 notifications by default, capped at 60 seconds/100
notifications. Complete-file tools are capped at 1 MiB; larger files use
chunked transfers. Domain Error values remain distinct from UA service
failures.

**Versioning:** the seven Vision/MachineVision/MCP packages and their
Debug variants follow the repository root version instead of being
forced to preview. Vision.OpenUsd and its descendants remain
preview-only. Development builds still inherit the root prerelease
version. No release version, tag, release branch, publication policy, or
feed promotion is changed.

**Review actions:** all fourteen review threads have action/evidence
replies and are resolved. Changes include the unified guide, Perception
namespace, separate Part 2 packages and final naming, multi-system
ownership explanation, interrupted-write cleanup, observer failure
isolation, complete MCP parameter descriptions, and explicit package
inventory. The preview-layout migration topic and the requested
ReleaseProcess caveat were removed. The test Publish collector now
retries recognized transient failures within one cancellation budget and
propagates other exceptions. Commit 69b1f5db9 applies the requested
short loader names and renames standalone hosting to `AddMachineVision`,
with callers, tests and documentation updated. The intervening master
merge is preserved.

### Verification

**Latest API naming changes, verified locally:**

| Scope | Result |
| --- | --- |
| Full Vision suite, net10 | 572 passed, 1 existing skip, 0 failed |
| Full Vision suite, net48 | 515 passed, 0 skipped, 0 failed |
| Final loader/hosting cases after cross-TFM null-guard adjustment | 9
passed, 0 failed, 0 skipped |
| Machine Vision MCP and profile cases | 198 passed, 0 failed, 0 skipped
|
| Main and MCP AOT test-project compilation | Both built with 0
warnings/errors |
| MCP AOT companion, managed execution | 5 passed, 0 failed, 0 skipped;
not claimed as native execution |

`ModelLoaderNamesRegisterTypedFactories`,
`ModelLoaderNamesRejectNullArguments`, and
`GeneratedModelsLoadTogetherAndCreateTypedInstances` cover all six
loader overloads, fluent return identities, typed instances, namespace
coexistence and null guards. Existing standalone Part 2 tests verify
idempotent registration, one-owner enforcement and null handling through
`AddMachineVision`. No source-generator implementation, CLR namespace,
wire identity or model payload was changed for these naming updates.

The current 69b1f5db9 revision is running
[CI](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/38165826937),
[package
validation](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/38165823359),
[MCP
usability](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/38165826874),
[CodeQL](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/38165826906),
and [Images
CI](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/38165826884).
These runs are not claimed as completed results.

**Earlier completed verification:** all seven default-TFM package
archives were inspected after the package rename: exact IDs, 27 clean
DLLs, correct dependencies/readmes/licenses, and unchanged pinned model
hashes. [CI on
c75ec4fa6](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/38142519760)
passed, including the formerly failing Linux batch and required summary.
Its unchanged coverage gate passed at **88.56% lines, 78.96% branches,
84.28% patch** against the 75% patch floor. The later
bounded-Publish-helper regressions reproduced 13 failures before the fix
and passed afterward; the full mainline triggering fixture passed 67
tests on each of net10/net48. These are historical results, not current
full-matrix results.

<details>
<summary>Executed API naming validation commands and outcomes</summary>

Run from the worktree root using the established artifact trees.
Dependency builds were performed before the no-build full net10 run; the
focused loader/hosting selection was rebuilt and rerun after the final
null-guard adjustment.

```powershell
$files = 'C:\Users\mschier\.copilot\session-state\deb2ba10-b0e9-4a44-8783-8331bc850814\files'
$env:DOTNET_CLI_USE_MSBUILD_SERVER = '0'
$env:TEMP = 'C:\Temp\mv-deb2\followup'
$env:TMP = $env:TEMP

# Passed: 572; Failed: 0; Skipped: 1.
dotnet test tests\Opc.Ua.Vision.Tests\Opc.Ua.Vision.Tests.csproj -c Release -f net10.0 --no-build --no-restore --artifacts-path artifacts\vision-followup -p:CustomTestTarget=net10.0 -p:UseSharedCompilation=false -m:1 -nr:false --logger 'console;verbosity=minimal' --logger trx --results-directory "$files\vision-api-names-net10" -- 'NUnit.WorkDirectory=C:\Temp\mv-deb2\followup'

# Passed: 9; Failed: 0; Skipped: 0, on the final source.
dotnet test tests\Opc.Ua.Vision.Tests\Opc.Ua.Vision.Tests.csproj -c Release -f net10.0 --no-restore --artifacts-path artifacts\vision-followup -p:CustomTestTarget=net10.0 -p:UseSharedCompilation=false -m:1 -nr:false --filter 'FullyQualifiedName~MachineVisionModelTests|FullyQualifiedName~StandalonePartTwoRegistrationUsesOneOwnerAndOneModelProvider|FullyQualifiedName~StandalonePartTwoRequiresRegistrationAndRejectsCompetingOwnership' --logger 'console;verbosity=minimal' --logger trx --results-directory "$files\vision-api-names-final-model" -- 'NUnit.WorkDirectory=C:\Temp\mv-deb2\followup'

# Passed: 198; Failed: 0; Skipped: 0.
dotnet test tests\Opc.Ua.Tools.Tests\Opc.Ua.Tools.Tests.csproj -c Release -f net10.0 --no-restore --artifacts-path artifacts\vision-followup -p:CustomTestTarget=net10.0 -p:UseSharedCompilation=false -m:1 -nr:false --filter 'FullyQualifiedName~VisionMachineToolsTests|FullyQualifiedName~McpHostBuilderTests|FullyQualifiedName~McpToolProfileCompositionTests' --logger 'console;verbosity=minimal' --logger trx --results-directory "$files\vision-api-names-final-mcp" -- 'NUnit.WorkDirectory=C:\Temp\mv-deb2\followup'

$env:TEMP = 'C:\Temp\mv-deb2\followup48'
$env:TMP = $env:TEMP

# Passed: 515; Failed: 0; Skipped: 0.
dotnet test tests\Opc.Ua.Vision.Tests\Opc.Ua.Vision.Tests.csproj -c Debug -f net48 --no-restore --artifacts-path "$files\solution-net48-artifacts" -p:CustomTestTarget=net48 -p:UseSharedCompilation=false -m:1 -nr:false --logger 'console;verbosity=minimal' --logger trx --results-directory "$files\vision-api-names-net48-final" -- 'NUnit.WorkDirectory=C:\Temp\mv-deb2\followup48'
```

Opt-in long-running/stress/durable tiers have not been rerun locally;
the unqualified **all tests** checklist item remains open. Original
implementation matrix counts are not presented as current results.

</details>

## Related Issues

- Fixes #4732.

The requester reviewed and approved the implementation plan and
subsequent packaging/API decisions in the development session. The
tracking issue records the design; maintainer architectural
discussion/sign-off there is still pending. This PR remains a draft.

## Checklist

_Put an `x` in the boxes that apply. You can complete these step by step
after opening the PR._

- [ ] 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.
- [ ] 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.
- [x] I have addressed **all** PR feedback received.
2026-10-12 07:01:27 +00:00

347 lines
22 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.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NUnit.Framework;
using Opc.Ua.Client;
using Opc.Ua.Client.StateMachines;
using Opc.Ua.Client.Subscriptions;
using Opc.Ua.Machinery.Server;
using Opc.Ua.Server.Hosting;
using Opc.Ua.Vision.Client;
using Opc.Ua.Vision.MachineVision;
using Opc.Ua.Vision.Server;
namespace Opc.Ua.Vision.Tests
{
public sealed partial class MachineVisionRuntimeTests
{
[Test]
public void MachineryCompositionRequiresExistingProviderRegistration()
{
var services = new ServiceCollection();
IOpcUaServerBuilder builder = services.AddOpcUa()
.AddServer(options => options.ApplicationName = "MachineVisionRegistration");
Assert.Throws<InvalidOperationException>(() => builder.AddVisionToMachinery());
builder.AddMachinery(options => options.Parts = MachineryParts.BuildingBlocks);
Assert.DoesNotThrow(() => builder.AddVisionToMachinery());
}
[Test]
public void StandaloneAssetsRejectASecondMachineryOwner()
{
var services = new ServiceCollection();
IOpcUaServerBuilder builder = services.AddOpcUa()
.AddServer(options => options.ApplicationName = "MachineVisionRegistration")
.AddMachinery(options => options.Parts = MachineryParts.BuildingBlocks);
Assert.Throws<InvalidOperationException>(() => builder.AddVision(
options => options.MachineVisionParts = MachineVisionParts.Assets).AddMachineVision());
}
[TestCase(false)]
[TestCase(true)]
[Category("Integration")]
[NonParallelizable]
public async Task CompositionSupportsBothPartsAndSessionFileCleanupOverTcpAsync(bool machineryOwner)
{
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(60));
CancellationToken ct = deadline.Token;
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
string url = $"opc.tcp://localhost:{port}/MachineVision";
string root = Path.Combine(Path.GetTempPath(), "MachineVisionWire-" + Guid.NewGuid().ToString("N"));
HostApplicationBuilder builder = Host.CreateApplicationBuilder();
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(LogLevel.Warning);
MachineVisionSystemHandle? runtime = null;
MachineVisionAssetHandle? asset = null;
IOpcUaServerBuilder serverBuilder = builder.Services.AddOpcUa()
.AddServer(options =>
{
options.ApplicationName = "MachineVisionWireServer";
options.ApplicationUri = "urn:opcfoundation:tests:machinevision:server";
options.PkiRoot = Path.Combine(root, "server");
options.AutoAcceptUntrustedCertificates = true;
options.IncludeUnsecurePolicyNone = true;
options.EndpointUrls.Add(url);
});
if (machineryOwner)
{
serverBuilder.AddMachinery(options => options.Parts = MachineryParts.BuildingBlocks)
.AddVisionToMachinery()
.ConfigureVisionFor<MachineryNodeManager>(ConfigureAsync);
}
else
{
serverBuilder.AddVision(options =>
options.MachineVisionParts = MachineVisionParts.Control | MachineVisionParts.Assets)
.AddMachineVision()
.ConfigureVision(ConfigureAsync);
}
async ValueTask ConfigureAsync(IVisionBuildContext vision, CancellationToken token)
{
runtime = await vision.AddMachineVisionSystemAsync(
"Inspection", Provider().Object, cancellationToken: token).ConfigureAwait(false);
asset = await vision.AddMachineVisionAsset("InspectionAsset")
.WithIdentification(Identification("wire", "urn:opcfoundation:tests:machinevision:wire"))
.RepresentsSameSystem(runtime.State)
.BuildAsync(token).ConfigureAwait(false);
}
using IHost server = builder.Build();
try
{
await server.StartAsync(ct).ConfigureAwait(false);
var services = new ServiceCollection();
services.AddOpcUa().AddClient(options =>
{
options.ApplicationName = "MachineVisionWireClient";
options.ApplicationUri = "urn:opcfoundation:tests:machinevision:client";
options.PkiRoot = Path.Combine(root, "client");
options.AutoAcceptUntrustedCertificates = true;
options.Session = new ManagedSessionOptions
{
SessionName = "MachineVisionWireClient",
Endpoint = new ConfiguredEndpoint(null, new EndpointDescription
{
EndpointUrl = url,
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None
}, null)
};
}).AddVisionClient();
await using ServiceProvider serviceProvider = services.BuildServiceProvider();
VisionClient visionClient = await serviceProvider
.GetRequiredService<Func<CancellationToken, Task<VisionClient>>>()(ct).ConfigureAwait(false);
Assert.That(visionClient.Session, Is.InstanceOf<ManagedSession>());
var session = (ManagedSession)visionClient.Session;
await using (session.ConfigureAwait(false))
{
DataValue conformance = await session.ReadValueAsync(
VariableIds.Server_ServerCapabilities_ConformanceUnits, ct)
.ConfigureAwait(false);
Assert.That(conformance.WrappedValue.TryGetValue(out ArrayOf<QualifiedName> units), Is.True);
Assert.That(units.ToArray(), Does.Contain(new QualifiedName("VSA Basic",
(ushort)session.NamespaceUris.GetIndex(MachineVisionModels.AssetNamespaceUri))));
Assert.That(units.ToArray(), Does.Contain(new QualifiedName("Automatic Mode",
(ushort)session.NamespaceUris.GetIndex(MachineVisionModels.ControlNamespaceUri))));
MachineVisionClient client = visionClient.MachineVision();
var systems = new List<VisionNodeEntry>();
await foreach (VisionNodeEntry system in client.EnumerateSystemsAsync(cancellationToken: ct)
.ConfigureAwait(false))
{
systems.Add(system);
}
Assert.That(systems, Has.Count.EqualTo(1));
Assert.That(systems[0].NodeId, Is.EqualTo(runtime!.State.NodeId));
var assets = new List<VisionNodeEntry>();
await foreach (VisionNodeEntry entry in client.EnumerateAssetsAsync(cancellationToken: ct)
.ConfigureAwait(false))
{
assets.Add(entry);
}
Assert.That(assets, Has.Count.EqualTo(1));
Assert.That(assets[0].NodeId, Is.EqualTo(asset!.State.NodeId));
ArrayOf<NodeId> linked = await client.GetSameEntityNodesAsync(asset.State.NodeId, ct)
.ConfigureAwait(false);
Assert.That(linked.ToArray(), Does.Contain(runtime.State.NodeId));
MachineVisionSystemClient systemClient = client.System(runtime.State.NodeId);
VisionStateMachineTypeClient control = await systemClient.ControlAsync(ct).ConfigureAwait(false);
Assert.That(await control.SelectModeAutomaticAsync(ct).ConfigureAwait(false), Is.Zero);
using var content = new MemoryStream([1, 2, 3]);
RecipeIdInternalDataType recipe = await systemClient.UploadRecipeAsync(
new RecipeIdExternalDataType { Id = "wire-recipe" },
new ProductIdDataType { Id = "wire-product" }, content, ct).ConfigureAwait(false);
RecipeManagementTypeClient recipes = await systemClient.RecipesAsync(ct).ConfigureAwait(false);
(RecipeIdInternalDataType? internalIdOut, bool isCompleted, int error) =
await recipes.PrepareRecipeAsync(new RecipeIdExternalDataType(), recipe, ct)
.ConfigureAwait(false);
Assert.That(error, Is.Zero);
Assert.That(isCompleted, Is.True);
VisionAutomaticModeStateMachineTypeClient automatic = await systemClient.AutomaticAsync(ct)
.ConfigureAwait(false);
FiniteStateSnapshot ready = await automatic.GetCurrentFiniteStateAsync(ct).ConfigureAwait(false);
Assert.That(ready.CurrentState.Text, Is.EqualTo("Ready"));
using var configurationContent = new MemoryStream([9, 8, 7]);
ConfigurationIdDataType configuration = await systemClient.UploadConfigurationAsync(
new ConfigurationIdDataType { Id = "wire-configuration" }, configurationContent, ct)
.ConfigureAwait(false);
ConfigurationManagementTypeClient configurations = await systemClient.ConfigurationsAsync(ct)
.ConfigureAwait(false);
Assert.That(await configurations.ActivateConfigurationAsync(configuration, ct)
.ConfigureAwait(false), Is.Zero);
(uint configurationHandle, ConfigurationDataType configuration, int error) configured =
await configurations.GetConfigurationByIdAsync(configuration, 0, ct)
.ConfigureAwait(false);
Assert.That(configured.error, Is.Zero);
Assert.That(configured.configuration.ExternalId.Id, Is.EqualTo("wire-configuration"));
Assert.That(configured.configuration.HasTransferableDataOnFile, Is.True);
Assert.That(await configurations.ReleaseConfigurationHandleAsync(configured.configurationHandle, ct)
.ConfigureAwait(false), Is.Zero);
ServiceResultException? activeRemoval = Assert.ThrowsAsync<ServiceResultException>(async () =>
await configurations.RemoveConfigurationAsync(configuration, ct).ConfigureAwait(false));
Assert.That(activeRemoval!.StatusCode, Is.EqualTo(StatusCodes.BadInvalidState));
await runtime.PublishResultAsync(new ResultDataType
{
ResultId = new ResultIdDataType { Id = "wire-download" },
ResultState = 77,
InternalConfigurationId = configuration,
ResultContent = [Variant.From(123)],
EncodingMask = (uint)ResultDataTypeFields.ResultContent
}, ByteString.From(new byte[] { 5, 4, 3, 2, 1 }), ct).ConfigureAwait(false);
using var download = new MemoryStream();
await systemClient.DownloadResultAsync(
new ResultIdDataType { Id = "wire-download" }, download, ct).ConfigureAwait(false);
Assert.That(download.ToArray(), Is.EqualTo(new byte[] { 5, 4, 3, 2, 1 }));
ResultManagementTypeClient results = await systemClient.ResultsAsync(ct).ConfigureAwait(false);
(bool hasTransferableDataOnFile, uint resultHandle, bool isPartial, bool isSimulated,
int resultState, MeasIdDataType measId, PartIdDataType partId,
RecipeIdExternalDataType externalRecipeId, RecipeIdInternalDataType internalRecipeId,
ProductIdDataType productId, ConfigurationIdDataType externalConfigurationId,
ConfigurationIdDataType internalConfigurationId, JobIdDataType jobId, DateTimeUtc creationTime,
ProcessingTimesDataType processingTimes, ArrayOf<Variant> resultContent,
int error) components = await results.GetResultComponentsByIdAsync(
new ResultIdDataType { Id = "wire-download" }, 0, ct).ConfigureAwait(false);
Assert.That(components.error, Is.Zero);
Assert.That(components.resultState, Is.EqualTo(77));
Assert.That(components.hasTransferableDataOnFile, Is.True);
Assert.That(components.resultContent[0].TryGetValue(out int value), Is.True);
Assert.That(value, Is.EqualTo(123));
Assert.That(await results.ReleaseResultHandleAsync(components.resultHandle, ct)
.ConfigureAwait(false), Is.Zero);
SafetyStateManagementTypeClient safety = await systemClient.SafetyAsync(ct).ConfigureAwait(false);
Assert.That(await safety.ReportSafetyStateAsync(true, "test interlock", ct)
.ConfigureAwait(false), Is.Zero);
Assert.That(runtime.State.SafetyStateManagement!.VisionSafetyTriggered!.Value, Is.True);
MachineVisionAssetSnapshot snapshot = await client.ReadAssetAsync(asset.State.NodeId,
cancellationToken: ct).ConfigureAwait(false);
Assert.That(snapshot.Values.Count, Is.GreaterThan(0));
MachineVisionCapabilities capabilities = await client.ReadCapabilitiesAsync(
runtime.State.NodeId, ct).ConfigureAwait(false);
Assert.That(capabilities.SupportsControl, Is.True);
Assert.That(capabilities.SupportsAssets, Is.True);
Assert.That(capabilities.Interfaces.ToArray(), Has.Some.Matches<MachineVisionInterfaceCapability>(
member => member.Path == "RecipeManagement/RecipeTransfer" && !member.NodeId.IsNull));
MachineVisionStatusSnapshot status = await client.ReadStatusAsync(runtime.State.NodeId, ct)
.ConfigureAwait(false);
Assert.That(status.Values.Count, Is.EqualTo(5));
Assert.That(status.Values[3].Value.WrappedValue.TryGetValue(out bool safetyTriggered), Is.True);
Assert.That(safetyTriggered, Is.True);
MachineVisionRelationshipPage relations = await client.ReadRelationshipsAsync(
asset.State.NodeId, MachineVisionRelationship.SameEntity, cancellationToken: ct)
.ConfigureAwait(false);
Assert.That(relations.IsComplete, Is.True);
Assert.That(relations.References.Count, Is.EqualTo(1));
Assert.That(ExpandedNodeId.ToNodeId(relations.References[0].NodeId, session.NamespaceUris),
Is.EqualTo(runtime.State.NodeId));
(RecipeIdInternalDataType _, NodeId recipeNodeId, NodeId _, bool _, int recipeError) =
await recipes.AddRecipeAsync(new RecipeIdExternalDataType { Id = "session-file" },
new ProductIdDataType(), ct).ConfigureAwait(false);
Assert.That(recipeError, Is.Zero);
var recipeProxy = new RecipeTypeClient(session, recipeNodeId, visionClient.Telemetry);
FileTypeClient file = await recipeProxy.GetHandleAsync(visionClient.Telemetry, ct)
.ConfigureAwait(false) ?? throw new InvalidOperationException("The recipe file is missing.");
uint writer = await file.OpenAsync(6, ct).ConfigureAwait(false);
await file.WriteAsync(writer, ByteString.From(new byte[] { 1, 2, 3 }), ct).ConfigureAwait(false);
await file.CloseAsync(writer, ct).ConfigureAwait(false);
writer = await file.OpenAsync(6, ct).ConfigureAwait(false);
await file.WriteAsync(writer, ByteString.From(new byte[] { 9 }), ct).ConfigureAwait(false);
NodeId closedSessionId = session.SessionId;
ConfiguredEndpoint endpoint = session.ConfiguredEndpoint;
await runtime.ReportErrorAsync("wire-observation", new LocalizedText("Camera unavailable"),
true, persistent: true, cancellationToken: ct).ConfigureAwait(false);
Assert.That(session.TryGetSubscriptionManager(out ISubscriptionManager? subscriptions), Is.True);
int existingSubscriptions = subscriptions!.Count;
MachineVisionObservation observation = await client.ObserveAsync(
ObjectIds.Server,
new MachineVisionObservationOptions
{
Mode = MachineVisionObservationMode.Conditions,
RefreshConditions = true,
MaximumNotifications = 1
}, ct).ConfigureAwait(false);
Assert.That(observation.Events.Count, Is.EqualTo(1));
MachineVisionObservedEvent conditionEvent = observation.Events[0];
Assert.That(conditionEvent.ConditionId.IsNull, Is.False);
Assert.That(conditionEvent.EventId.Length, Is.GreaterThan(0));
Assert.That(conditionEvent.Decoded, Is.InstanceOf<VisionPersistentErrorConditionTypeRecord>());
Assert.That(subscriptions.Count, Is.EqualTo(existingSubscriptions));
var condition = new AcknowledgeableConditionTypeClient(
session, conditionEvent.ConditionId, visionClient.Telemetry);
await condition.AcknowledgeAsync(conditionEvent.EventId, new LocalizedText("Observed"), ct)
.ConfigureAwait(false);
await session.DefaultStreaming.DisposeAsync().ConfigureAwait(false);
await session.CloseAsync(ct).ConfigureAwait(false);
await using ManagedSession replacement = await serviceProvider
.GetRequiredService<IManagedSessionFactory>().ConnectAsync(endpoint, ct).ConfigureAwait(false);
Assert.That(replacement.SessionId, Is.Not.EqualTo(closedSessionId));
var survivingFile = new FileTypeClient(replacement, file.ObjectId, visionClient.Telemetry);
uint reader = await survivingFile.OpenAsync(1, ct).ConfigureAwait(false);
ByteString preserved = await survivingFile.ReadAsync(reader, 3, ct).ConfigureAwait(false);
Assert.That(preserved.ToArray(), Is.EqualTo(new byte[] { 1, 2, 3 }),
"Closing the session must release the writer without committing its abandoned bytes.");
await survivingFile.CloseAsync(reader, ct).ConfigureAwait(false);
writer = await survivingFile.OpenAsync(6, ct).ConfigureAwait(false);
await survivingFile.WriteAsync(writer, ByteString.From(new byte[] { 4, 5 }), ct)
.ConfigureAwait(false);
await survivingFile.CloseAsync(writer, ct).ConfigureAwait(false);
reader = await survivingFile.OpenAsync(1, ct).ConfigureAwait(false);
ByteString replaced = await survivingFile.ReadAsync(reader, 2, ct).ConfigureAwait(false);
Assert.That(replaced.ToArray(), Is.EqualTo(new byte[] { 4, 5 }));
await survivingFile.CloseAsync(reader, ct).ConfigureAwait(false);
await replacement.CloseAsync(ct).ConfigureAwait(false);
}
}
finally
{
await server.StopAsync(CancellationToken.None).ConfigureAwait(false);
server.Dispose();
if (Directory.Exists(root))
{
Directory.Delete(root, true);
}
}
}
}
}