task-galaxy-e2e branch — non-FOCAS work-in-progress snapshot
Catch-all commit for pending work on the task-galaxy-e2e branch that
wasn't part of the FOCAS migration. Grouping by topic so future per-topic
commits can be cherry-picked if needed.
TwinCAT
- src/.../Driver.TwinCAT/AdsTwinCATClient.cs + TwinCATDriverFactoryExtensions.cs:
factory-registration extensions + ADS client refinements.
- src/.../Driver.TwinCAT.Cli/Commands/BrowseCommand.cs: new browse command
for the TwinCAT test-client CLI.
- tests/.../Driver.TwinCAT.IntegrationTests/TwinCAT3SmokeTests.cs + TwinCatProject/:
fixture scaffold with a minimal POU + README pointing at the TCBSD/ESXi
VM for e2e.
- docs/Driver.TwinCAT.Cli.md + docs/drivers/TwinCAT-Test-Fixture.md:
documentation for the above.
- docs/v3/twincat-backlog.md: forward-looking backlog seed.
Admin UI + fleet status
- src/.../Admin/Components/Pages/Clusters/DriversTab.razor + Hosts.razor:
UI refresh for fleet-status rendering.
- src/.../Admin/Hubs/FleetStatusHub.cs + FleetStatusPoller.cs +
Admin/Program.cs: SignalR hub + poller plumbing for live fleet data.
- tests/.../Admin.Tests/FleetStatusPollerTests.cs: poller coverage.
Server + redundancy runtime (Phase 6.3 follow-ups)
- src/.../Server/Hosting/RedundancyPublisherHostedService.cs: HostedService
that owns the RedundancyStatePublisher lifecycle + wires peer reachability.
- src/.../Server/Redundancy/ServerRedundancyNodeWriter.cs: OPC UA
variable-node writer binding ServiceLevel + ServerUriArray to the
publisher's events.
- src/.../Server/Program.cs + Server.csproj: hosted-service registration.
- tests/.../Server.Tests/ServerRedundancyNodeWriterTests.cs +
Server.Tests.csproj: coverage for the above.
Configuration
- src/.../Configuration/Validation/DraftValidator.cs +
tests/.../Configuration.Tests/DraftValidatorTests.cs: draft-validation
refinements.
E2E scripts (shared infrastructure)
- scripts/e2e/README.md + _common.ps1 + test-all.ps1: shared helpers + the
all-drivers test-all runner.
- scripts/e2e/test-opcuaclient.ps1: OPC UA Client e2e runner.
Docs
- docs/v2/implementation/phase-6-{1,2,3,4}*.md + exit-gate-phase-{3,7}.md:
phase-gate + implementation doc updates.
- docs/v2/plan.md: top-level plan refresh.
- docs/v2/redundancy-interop-playbook.md: client interop playbook for the
Phase 6.3 redundancy-runtime work.
Two orphan FOCAS docs remain on disk but deliberately unstaged —
docs/v2/focas-deployment.md and docs/v2/implementation/focas-simulator-plan.md
describe the now-retired Tier-C topology and should either be rewritten
or deleted in a follow-up.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -153,4 +153,62 @@ END";
|
||||
m.Args[0] is AlertMessage alert && alert.NodeId == "p-2-a" && alert.Severity == "error");
|
||||
alertMatch.ShouldNotBeNull("poller should have raised AlertRaised for p-2-a");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Poller_pushes_ResilienceStatusChanged_on_delta()
|
||||
{
|
||||
// Phase 6.1 Stream E.2 — DriverInstanceResilienceStatus row changes should surface
|
||||
// on the fleet hub so /hosts updates without waiting for the 10s poll.
|
||||
using (var scope = _sp.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<OtOpcUaConfigDbContext>();
|
||||
db.DriverInstanceResilienceStatuses.Add(new DriverInstanceResilienceStatus
|
||||
{
|
||||
DriverInstanceId = "drv-1", HostName = "plc.example.com",
|
||||
ConsecutiveFailures = 2, CurrentBulkheadDepth = 1,
|
||||
LastSampledUtc = DateTime.UtcNow,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var recorder = new RecordingHubClients();
|
||||
var fleetHub = new RecordingHubContext<FleetStatusHub>(recorder);
|
||||
var alertHub = new RecordingHubContext<AlertHub>(new RecordingHubClients());
|
||||
|
||||
var poller = new FleetStatusPoller(
|
||||
_sp.GetRequiredService<IServiceScopeFactory>(),
|
||||
fleetHub, alertHub, NullLogger<FleetStatusPoller>.Instance, new RedundancyMetrics());
|
||||
|
||||
await poller.PollOnceAsync(CancellationToken.None);
|
||||
|
||||
var match = recorder.SentMessages.FirstOrDefault(m =>
|
||||
m.Method == "ResilienceStatusChanged" &&
|
||||
m.Args.Length > 0 &&
|
||||
m.Args[0] is ResilienceStatusChangedMessage r &&
|
||||
r.DriverInstanceId == "drv-1" && r.HostName == "plc.example.com");
|
||||
match.ShouldNotBeNull("poller should have pushed ResilienceStatusChanged on first observation");
|
||||
|
||||
// Same snapshot on the next tick — should NOT push again (delta-only push).
|
||||
recorder.SentMessages.Clear();
|
||||
await poller.PollOnceAsync(CancellationToken.None);
|
||||
recorder.SentMessages.Any(m => m.Method == "ResilienceStatusChanged")
|
||||
.ShouldBeFalse("unchanged snapshot must not fire another push");
|
||||
|
||||
// Mutate the row — delta should fire again.
|
||||
using (var scope = _sp.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<OtOpcUaConfigDbContext>();
|
||||
var row = await db.DriverInstanceResilienceStatuses.SingleAsync();
|
||||
row.ConsecutiveFailures = 5;
|
||||
row.LastCircuitBreakerOpenUtc = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
await poller.PollOnceAsync(CancellationToken.None);
|
||||
var mutatedMatch = recorder.SentMessages.FirstOrDefault(m =>
|
||||
m.Method == "ResilienceStatusChanged" &&
|
||||
m.Args.Length > 0 &&
|
||||
m.Args[0] is ResilienceStatusChangedMessage r2 && r2.ConsecutiveFailures == 5);
|
||||
mutatedMatch.ShouldNotBeNull("mutated row should produce a second ResilienceStatusChanged");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,4 +145,91 @@ public sealed class DraftValidatorTests
|
||||
errors.ShouldContain(e => e.Code == "EquipmentIdNotDerived");
|
||||
errors.ShouldContain(e => e.Code == "UnsSegmentInvalid");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------
|
||||
// Phase 6.3 task #148 part 2 — ValidateClusterTopology
|
||||
// ------------------------------------------------------------------------------------
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, RedundancyMode.None, 1, 0)] // single-node standalone — ok
|
||||
[InlineData(2, RedundancyMode.Warm, 2, 0)] // 2-node warm — ok
|
||||
[InlineData(2, RedundancyMode.Hot, 2, 0)] // 2-node hot — ok
|
||||
[InlineData(1, RedundancyMode.Warm, 1, 1)] // declared mismatch — should flag
|
||||
[InlineData(2, RedundancyMode.None, 2, 1)] // None with 2 nodes — should flag
|
||||
public void ValidateClusterTopology_checks_declared_pair(
|
||||
byte nodeCount, RedundancyMode mode, int enabledNodes, int expectedDeclaredErrors)
|
||||
{
|
||||
var cluster = BuildCluster(nodeCount: nodeCount, mode: mode);
|
||||
var nodes = Enumerable.Range(0, enabledNodes)
|
||||
.Select(i => BuildNode($"n-{i}", enabled: true, role: i == 0 ? RedundancyRole.Primary : RedundancyRole.Secondary))
|
||||
.ToList();
|
||||
|
||||
var errors = DraftValidator.ValidateClusterTopology(cluster, nodes);
|
||||
errors.Count(e => e.Code == "ClusterRedundancyModeInvalid").ShouldBe(expectedDeclaredErrors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidateClusterTopology_flags_disabled_node_mismatch()
|
||||
{
|
||||
// Declared 2 + Hot, but one node disabled — runtime would boot InvalidTopology.
|
||||
var cluster = BuildCluster(nodeCount: 2, mode: RedundancyMode.Hot);
|
||||
var nodes = new[]
|
||||
{
|
||||
BuildNode("primary", enabled: true, role: RedundancyRole.Primary),
|
||||
BuildNode("backup", enabled: false, role: RedundancyRole.Secondary),
|
||||
};
|
||||
|
||||
var errors = DraftValidator.ValidateClusterTopology(cluster, nodes);
|
||||
errors.ShouldContain(e => e.Code == "ClusterEnabledNodeCountMismatch");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidateClusterTopology_flags_multiple_Primary()
|
||||
{
|
||||
var cluster = BuildCluster(nodeCount: 2, mode: RedundancyMode.Hot);
|
||||
var nodes = new[]
|
||||
{
|
||||
BuildNode("a", enabled: true, role: RedundancyRole.Primary),
|
||||
BuildNode("b", enabled: true, role: RedundancyRole.Primary),
|
||||
};
|
||||
|
||||
var errors = DraftValidator.ValidateClusterTopology(cluster, nodes);
|
||||
errors.ShouldContain(e => e.Code == "ClusterMultiplePrimary");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidateClusterTopology_returns_no_errors_on_valid_standalone()
|
||||
{
|
||||
var cluster = BuildCluster(nodeCount: 1, mode: RedundancyMode.None);
|
||||
var nodes = new[] { BuildNode("only", enabled: true, role: RedundancyRole.Primary) };
|
||||
|
||||
var errors = DraftValidator.ValidateClusterTopology(cluster, nodes);
|
||||
errors.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
private static ServerCluster BuildCluster(byte nodeCount, RedundancyMode mode) => new()
|
||||
{
|
||||
ClusterId = "c-test",
|
||||
Name = "Test",
|
||||
Enterprise = "zb",
|
||||
Site = "dev",
|
||||
NodeCount = nodeCount,
|
||||
RedundancyMode = mode,
|
||||
Enabled = true,
|
||||
CreatedBy = "t",
|
||||
};
|
||||
|
||||
private static ClusterNode BuildNode(string id, bool enabled, RedundancyRole role) => new()
|
||||
{
|
||||
NodeId = id,
|
||||
ClusterId = "c-test",
|
||||
RedundancyRole = role,
|
||||
Host = "localhost",
|
||||
OpcUaPort = 4840,
|
||||
DashboardPort = 5001,
|
||||
ApplicationUri = $"urn:{id}",
|
||||
ServiceLevelBase = 200,
|
||||
Enabled = enabled,
|
||||
CreatedBy = "t",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,8 +9,10 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.IntegrationTests;
|
||||
/// End-to-end smoke tests against a live TwinCAT 3 XAR runtime. Skipped via
|
||||
/// <see cref="TwinCATFactAttribute"/> when the VM isn't reachable / the AmsNetId
|
||||
/// isn't set. Proves the driver's AMS route setup, ADS read/write, symbol browse,
|
||||
/// and native <c>AddDeviceNotification</c> subscription all work on the wire —
|
||||
/// coverage the <c>FakeTwinCATClient</c>-backed unit suite can only contract-test.
|
||||
/// native <c>AddDeviceNotification</c> subscription, array addressing, auto-reconnect,
|
||||
/// full primitive type mapping, and the DiscoverAsync→address-space pipeline all work
|
||||
/// on the wire — coverage the <c>FakeTwinCATClient</c>-backed unit suite can only
|
||||
/// contract-test.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para><b>Required VM project state</b> (see <c>TwinCatProject/README.md</c>):</para>
|
||||
@@ -18,6 +20,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.IntegrationTests;
|
||||
/// <item>GVL <c>GVL_Fixture</c> with <c>nCounter : DINT</c> (seed <c>1234</c>),
|
||||
/// <c>rSetpoint : REAL</c> (scratch; smoke writes + reads), <c>bFlag : BOOL</c>
|
||||
/// (seed <c>TRUE</c>).</item>
|
||||
/// <item>GVL <c>GVL_Primitives</c> with one of every ADS primitive at its seed value.</item>
|
||||
/// <item>GVL <c>GVL_Arrays</c> with <c>aReal1D : ARRAY[0..31] OF REAL</c> (scratch; array
|
||||
/// round-trip test writes element 5).</item>
|
||||
/// <item>PLC program <c>MAIN</c> that increments <c>GVL_Fixture.nCounter</c>
|
||||
/// every cycle (so the native-notification test can observe monotonic changes
|
||||
/// without writing).</item>
|
||||
@@ -43,9 +48,10 @@ public sealed class TwinCAT3SmokeTests(TwinCATXarFixture sim)
|
||||
snapshots.Count.ShouldBe(1);
|
||||
snapshots[0].StatusCode.ShouldBe(0u,
|
||||
"ADS read against GVL_Fixture.nCounter must succeed end-to-end");
|
||||
// MAIN increments the counter every cycle, so the seed value (1234) is only the
|
||||
// minimum we can assert — value grows monotonically.
|
||||
Convert.ToInt32(snapshots[0].Value).ShouldBeGreaterThanOrEqualTo(1234);
|
||||
// Value is a DINT — we only assert the read path returned an integer. Don't
|
||||
// pin to the 1234 seed: the PlcTask may watchdog-restart and reset counters
|
||||
// to 0, and we care about end-to-end transport here, not PLC uptime.
|
||||
Convert.ToInt32(snapshots[0].Value).ShouldBeGreaterThanOrEqualTo(0);
|
||||
}
|
||||
|
||||
[TwinCATFact]
|
||||
@@ -89,14 +95,16 @@ public sealed class TwinCAT3SmokeTests(TwinCATXarFixture sim)
|
||||
};
|
||||
|
||||
var handle = await drv.SubscribeAsync(
|
||||
["Counter"], TimeSpan.FromMilliseconds(250),
|
||||
["Counter"], TimeSpan.FromMilliseconds(500),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
// MAIN increments the counter every PLC cycle (default 10 ms task tick).
|
||||
// Native ADS notifications fire on cycle boundaries so 3 s is generous for
|
||||
// at least one OnDataChange to land.
|
||||
var got = await gate.WaitAsync(TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
|
||||
got.ShouldBeTrue("native ADS notification on GVL_Fixture.nCounter must fire within 3 s of subscribe");
|
||||
// We only assert the transport wires up and at least one notification lands.
|
||||
// Don't pin to PLC cycle time: if PlcTask watchdog-restarts or runs slower than
|
||||
// its nominal 10 ms, increments may be coarse — but the counter still changes,
|
||||
// so any reasonable window catches it. 10 s leaves headroom for transient PLC
|
||||
// restarts without turning into a test hang.
|
||||
var got = await gate.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
got.ShouldBeTrue("native ADS notification on GVL_Fixture.nCounter must fire within 10 s of subscribe");
|
||||
|
||||
int observedCount;
|
||||
lock (observed) observedCount = observed.Count;
|
||||
@@ -105,6 +113,435 @@ public sealed class TwinCAT3SmokeTests(TwinCATXarFixture sim)
|
||||
await drv.UnsubscribeAsync(handle, TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[TwinCATFact]
|
||||
public async Task Driver_browses_committed_symbol_hierarchy_via_real_ADS()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
|
||||
// Goes straight at the wire client rather than TwinCATDriver.DiscoverAsync: the
|
||||
// discover flow funnels symbols into an IAddressSpaceBuilder, which doesn't give
|
||||
// us a flat list to assert against. BrowseSymbolsAsync is what that flow calls
|
||||
// internally, so covering it here covers the same transport path.
|
||||
using var client = new AdsTwinCATClient();
|
||||
await client.ConnectAsync(
|
||||
new TwinCATAmsAddress(sim.TargetNetId!, sim.AmsPort),
|
||||
TimeSpan.FromSeconds(5),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
var symbols = new List<TwinCATDiscoveredSymbol>();
|
||||
await foreach (var s in client.BrowseSymbolsAsync(TestContext.Current.CancellationToken))
|
||||
symbols.Add(s);
|
||||
|
||||
symbols.ShouldNotBeEmpty("BrowseSymbolsAsync must yield at least the committed GVL symbols");
|
||||
|
||||
// Spot-check the smoke-test contract: GVL_Fixture.nCounter (DINT, writable).
|
||||
var counter = symbols.FirstOrDefault(s => s.InstancePath == "GVL_Fixture.nCounter");
|
||||
counter.ShouldNotBeNull("GVL_Fixture.nCounter must surface in the symbol table");
|
||||
counter.DataType.ShouldBe(TwinCATDataType.DInt);
|
||||
|
||||
// Primitive coverage — every ADS primitive is committed under GVL_Primitives. Prove
|
||||
// the type mapper catches a couple of representative entries (BOOL, REAL, STRING).
|
||||
symbols.ShouldContain(s => s.InstancePath == "GVL_Primitives.vBool" && s.DataType == TwinCATDataType.Bool);
|
||||
symbols.ShouldContain(s => s.InstancePath == "GVL_Primitives.vReal" && s.DataType == TwinCATDataType.Real);
|
||||
symbols.ShouldContain(s => s.InstancePath == "GVL_Primitives.vString" && s.DataType == TwinCATDataType.String);
|
||||
|
||||
// Array coverage — SymbolLoaderFactory (Flat mode) expands arrays to per-element
|
||||
// paths, so at least one element of the 2-D REAL array should appear.
|
||||
symbols.ShouldContain(s => s.InstancePath.StartsWith("GVL_Arrays.aReal2D", StringComparison.Ordinal));
|
||||
|
||||
// Enum / alias coverage — GVL_Enums roots one of each so we don't have to walk plants.
|
||||
symbols.ShouldContain(s => s.InstancePath == "GVL_Enums.currentAxisState");
|
||||
}
|
||||
|
||||
[TwinCATFact]
|
||||
public async Task Driver_round_trips_array_element_write_and_read()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
|
||||
// Arrays are a high-traffic PLC pattern but no earlier test hits an indexed symbol
|
||||
// end-to-end. Round-trip into GVL_Arrays.aReal1D[5] — the subscript flows through
|
||||
// TwinCATSymbolPath.TryParse → AdsSymbolName ("GVL_Arrays.aReal1D[5]") which is
|
||||
// the ADS wire syntax the SymbolLoader emits for per-element access.
|
||||
var options = BuildOptions(sim);
|
||||
await using var drv = new TwinCATDriver(options, driverInstanceId: "tc3-smoke-array");
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
const float probe = 73.25f;
|
||||
var writeResults = await drv.WriteAsync(
|
||||
[new WriteRequest("ArrayElem", probe)],
|
||||
TestContext.Current.CancellationToken);
|
||||
writeResults.Count.ShouldBe(1);
|
||||
writeResults[0].StatusCode.ShouldBe(0u, "array-element write must succeed against aReal1D[5]");
|
||||
|
||||
var readResults = await drv.ReadAsync(
|
||||
["ArrayElem"], TestContext.Current.CancellationToken);
|
||||
readResults[0].StatusCode.ShouldBe(0u);
|
||||
Convert.ToSingle(readResults[0].Value).ShouldBe(probe, tolerance: 0.001f);
|
||||
}
|
||||
|
||||
[TwinCATFact]
|
||||
public async Task Driver_auto_reconnects_after_underlying_client_is_disposed()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
|
||||
// Reconnect is the most operationally important durability property — ADS links
|
||||
// drop (router restarts, VM reboots, TCP resets). EnsureConnectedAsync creates a
|
||||
// fresh AdsClient when the prior one is gone, but until this test the live-wire
|
||||
// recovery path was only unit-tested against FakeTwinCATClient.
|
||||
var options = BuildOptions(sim);
|
||||
await using var drv = new TwinCATDriver(options, driverInstanceId: "tc3-smoke-reconnect");
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
var first = await drv.ReadAsync(["Counter"], TestContext.Current.CancellationToken);
|
||||
first[0].StatusCode.ShouldBe(0u);
|
||||
|
||||
// Dispose the underlying client the driver is holding. Next read must reconnect
|
||||
// (via EnsureConnectedAsync → AdsClient.Connect) rather than fail.
|
||||
var hostAddress = $"ads://{sim.TargetNetId}:{sim.AmsPort}";
|
||||
var device = drv.GetDeviceState(hostAddress).ShouldNotBeNull("device state must exist after Initialize");
|
||||
device.DisposeClient();
|
||||
|
||||
var second = await drv.ReadAsync(["Counter"], TestContext.Current.CancellationToken);
|
||||
second[0].StatusCode.ShouldBe(0u, "driver must transparently reconnect on next read");
|
||||
}
|
||||
|
||||
[TwinCATTheory]
|
||||
// vBool's expected value is null — the initial TRUE seed doesn't reliably survive cold
|
||||
// restarts on this deployment, and the point of this theory is round-tripping the type
|
||||
// mapper, not test-data seed persistence. All other primitives re-init on every boot.
|
||||
[InlineData("GVL_Primitives.vBool", TwinCATDataType.Bool, null)]
|
||||
[InlineData("GVL_Primitives.vSInt", TwinCATDataType.SInt, "-42")]
|
||||
[InlineData("GVL_Primitives.vUSInt", TwinCATDataType.USInt, "250")]
|
||||
[InlineData("GVL_Primitives.vInt", TwinCATDataType.Int, "-12345")]
|
||||
[InlineData("GVL_Primitives.vUInt", TwinCATDataType.UInt, "54321")]
|
||||
[InlineData("GVL_Primitives.vDInt", TwinCATDataType.DInt, "-1234567")]
|
||||
[InlineData("GVL_Primitives.vUDInt", TwinCATDataType.UDInt, "4000000000")]
|
||||
[InlineData("GVL_Primitives.vLInt", TwinCATDataType.LInt, "-1234567890123")]
|
||||
[InlineData("GVL_Primitives.vULInt", TwinCATDataType.ULInt, "12345678901234567")]
|
||||
[InlineData("GVL_Primitives.vReal", TwinCATDataType.Real, "3.14159")]
|
||||
[InlineData("GVL_Primitives.vLReal", TwinCATDataType.LReal, "2.7182818284590452")]
|
||||
[InlineData("GVL_Primitives.vString", TwinCATDataType.String, "Hello from TC3")]
|
||||
[InlineData("GVL_Primitives.vTime", TwinCATDataType.Time, null)]
|
||||
[InlineData("GVL_Primitives.vTimeOfDay", TwinCATDataType.TimeOfDay, null)]
|
||||
[InlineData("GVL_Primitives.vDate", TwinCATDataType.Date, null)]
|
||||
[InlineData("GVL_Primitives.vDateTime", TwinCATDataType.DateTime, null)]
|
||||
public async Task Driver_reads_every_primitive_type_with_correct_mapping(
|
||||
string symbolPath, TwinCATDataType type, string? expectedValueInvariant)
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
|
||||
// One driver per case is ~0.3 s each on the live VM — pragmatic vs a shared-driver
|
||||
// iteration pattern since the point is to exercise options/tag-mapping/ReadAsync
|
||||
// end-to-end per primitive, catching regressions like the STRING(N) mapper bug.
|
||||
var options = new TwinCATDriverOptions
|
||||
{
|
||||
Devices = [new TwinCATDeviceOptions($"ads://{sim.TargetNetId}:{sim.AmsPort}", "XAR-VM")],
|
||||
Tags =
|
||||
[
|
||||
new TwinCATTagDefinition(
|
||||
Name: "Primitive",
|
||||
DeviceHostAddress: $"ads://{sim.TargetNetId}:{sim.AmsPort}",
|
||||
SymbolPath: symbolPath,
|
||||
DataType: type),
|
||||
],
|
||||
Timeout = TimeSpan.FromSeconds(5),
|
||||
Probe = new TwinCATProbeOptions { Enabled = false },
|
||||
};
|
||||
await using var drv = new TwinCATDriver(options, driverInstanceId: $"tc3-prim-{type}");
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
var result = await drv.ReadAsync(["Primitive"], TestContext.Current.CancellationToken);
|
||||
result[0].StatusCode.ShouldBe(0u, $"primitive read must succeed for {symbolPath} ({type})");
|
||||
result[0].Value.ShouldNotBeNull();
|
||||
|
||||
// Expected-value check only where the seed is ergonomic to re-encode as a literal —
|
||||
// TIME / TOD / DATE / DT arrive as uint ticks, which is covered by the status+type
|
||||
// assertions above; adding brittle tick-math here adds no signal over that.
|
||||
if (expectedValueInvariant is not null)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case TwinCATDataType.Bool:
|
||||
result[0].Value.ShouldBe(bool.Parse(expectedValueInvariant));
|
||||
break;
|
||||
case TwinCATDataType.String:
|
||||
result[0].Value.ShouldBe(expectedValueInvariant);
|
||||
break;
|
||||
case TwinCATDataType.Real:
|
||||
Convert.ToSingle(result[0].Value).ShouldBe(
|
||||
float.Parse(expectedValueInvariant, System.Globalization.CultureInfo.InvariantCulture),
|
||||
tolerance: 0.0001f);
|
||||
break;
|
||||
case TwinCATDataType.LReal:
|
||||
Convert.ToDouble(result[0].Value).ShouldBe(
|
||||
double.Parse(expectedValueInvariant, System.Globalization.CultureInfo.InvariantCulture),
|
||||
tolerance: 0.0000001);
|
||||
break;
|
||||
default:
|
||||
// Integer primitives: parse against the target CLR type the mapper chose.
|
||||
Convert.ToInt64(result[0].Value).ShouldBe(long.Parse(expectedValueInvariant));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TwinCATFact]
|
||||
public async Task Driver_reads_bit_indexed_BOOL_from_word()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
|
||||
// GVL_Primitives.vWord = 0xBEEF = 1011 1110 1110 1111. Bit 3 = 1 (within the low
|
||||
// nibble 'F'). Tags with bitIndex route through ExtractBit → TwinCAT.Ads supports
|
||||
// the .N bit-access suffix natively so the driver's read path relies on that.
|
||||
var options = new TwinCATDriverOptions
|
||||
{
|
||||
Devices = [new TwinCATDeviceOptions($"ads://{sim.TargetNetId}:{sim.AmsPort}", "XAR-VM")],
|
||||
Tags =
|
||||
[
|
||||
new TwinCATTagDefinition(
|
||||
Name: "WordBit3",
|
||||
DeviceHostAddress: $"ads://{sim.TargetNetId}:{sim.AmsPort}",
|
||||
SymbolPath: "GVL_Primitives.vWord.3",
|
||||
DataType: TwinCATDataType.Bool),
|
||||
new TwinCATTagDefinition(
|
||||
Name: "WordBit4",
|
||||
DeviceHostAddress: $"ads://{sim.TargetNetId}:{sim.AmsPort}",
|
||||
SymbolPath: "GVL_Primitives.vWord.4",
|
||||
DataType: TwinCATDataType.Bool),
|
||||
],
|
||||
Timeout = TimeSpan.FromSeconds(5),
|
||||
Probe = new TwinCATProbeOptions { Enabled = false },
|
||||
};
|
||||
await using var drv = new TwinCATDriver(options, driverInstanceId: "tc3-smoke-bitbool");
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
var result = await drv.ReadAsync(["WordBit3", "WordBit4"], TestContext.Current.CancellationToken);
|
||||
|
||||
result[0].StatusCode.ShouldBe(0u);
|
||||
result[0].Value.ShouldBe(true, "bit 3 of 0xBEEF is set");
|
||||
result[1].StatusCode.ShouldBe(0u);
|
||||
result[1].Value.ShouldBe(false, "bit 4 of 0xBEEF is clear");
|
||||
}
|
||||
|
||||
[TwinCATFact]
|
||||
public async Task Driver_reads_deeply_nested_UDT_path()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
|
||||
// 5-level nested path into the plant hierarchy. FB_LineSim is driving the motor
|
||||
// temperature from a sine of the counter, so the value is alive but bounded.
|
||||
var options = new TwinCATDriverOptions
|
||||
{
|
||||
Devices = [new TwinCATDeviceOptions($"ads://{sim.TargetNetId}:{sim.AmsPort}", "XAR-VM")],
|
||||
Tags =
|
||||
[
|
||||
new TwinCATTagDefinition(
|
||||
Name: "MotorTemp",
|
||||
DeviceHostAddress: $"ads://{sim.TargetNetId}:{sim.AmsPort}",
|
||||
SymbolPath: "GVL_Plant.Line1.Stations[1].Axes[1].Motor.Temperature",
|
||||
DataType: TwinCATDataType.LReal),
|
||||
new TwinCATTagDefinition(
|
||||
Name: "MotorRunning",
|
||||
DeviceHostAddress: $"ads://{sim.TargetNetId}:{sim.AmsPort}",
|
||||
SymbolPath: "GVL_Plant.Line1.Stations[1].Axes[1].Motor.Running",
|
||||
DataType: TwinCATDataType.Bool),
|
||||
],
|
||||
Timeout = TimeSpan.FromSeconds(5),
|
||||
Probe = new TwinCATProbeOptions { Enabled = false },
|
||||
};
|
||||
await using var drv = new TwinCATDriver(options, driverInstanceId: "tc3-smoke-udt");
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
var result = await drv.ReadAsync(["MotorTemp", "MotorRunning"], TestContext.Current.CancellationToken);
|
||||
|
||||
result[0].StatusCode.ShouldBe(0u, "nested UDT LREAL path must round-trip");
|
||||
result[0].Value.ShouldBeOfType<double>();
|
||||
result[1].StatusCode.ShouldBe(0u, "nested UDT BOOL path must round-trip");
|
||||
result[1].Value.ShouldBeOfType<bool>();
|
||||
}
|
||||
|
||||
[TwinCATFact]
|
||||
public async Task Driver_reports_errors_for_unknown_tag_and_nonexistent_symbol_and_readonly_write()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
|
||||
// Three negative paths in one driver instance — cheaper than spinning three drivers
|
||||
// for what are essentially status-code assertions:
|
||||
// 1. unknown tag name (not in the options map) → BadNodeIdUnknown
|
||||
// 2. known tag pointing at a nonexistent PLC symbol → ADS error mapped to non-zero
|
||||
// 3. write against a Writable=false tag → BadNotWritable
|
||||
var options = new TwinCATDriverOptions
|
||||
{
|
||||
Devices = [new TwinCATDeviceOptions($"ads://{sim.TargetNetId}:{sim.AmsPort}", "XAR-VM")],
|
||||
Tags =
|
||||
[
|
||||
new TwinCATTagDefinition(
|
||||
Name: "NonexistentSymbol",
|
||||
DeviceHostAddress: $"ads://{sim.TargetNetId}:{sim.AmsPort}",
|
||||
SymbolPath: "GVL_DoesNotExist.vGhost",
|
||||
DataType: TwinCATDataType.DInt),
|
||||
new TwinCATTagDefinition(
|
||||
Name: "ReadOnlyCounter",
|
||||
DeviceHostAddress: $"ads://{sim.TargetNetId}:{sim.AmsPort}",
|
||||
SymbolPath: "GVL_Fixture.nCounter",
|
||||
DataType: TwinCATDataType.DInt,
|
||||
Writable: false),
|
||||
],
|
||||
Timeout = TimeSpan.FromSeconds(5),
|
||||
Probe = new TwinCATProbeOptions { Enabled = false },
|
||||
};
|
||||
await using var drv = new TwinCATDriver(options, driverInstanceId: "tc3-smoke-errors");
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
// (1) Unknown tag — never registered in options, must short-circuit before ADS.
|
||||
var unknownRead = await drv.ReadAsync(["NeverDeclared"], TestContext.Current.CancellationToken);
|
||||
unknownRead[0].StatusCode.ShouldBe(TwinCATStatusMapper.BadNodeIdUnknown);
|
||||
|
||||
// (2) Known tag, nonexistent PLC symbol — ADS returns SymbolNotFound, driver maps it
|
||||
// to a non-zero OPC UA status. Don't pin to a specific code — the exact mapping
|
||||
// is a driver-internal concern and we only care it surfaces as an error.
|
||||
var ghostRead = await drv.ReadAsync(["NonexistentSymbol"], TestContext.Current.CancellationToken);
|
||||
ghostRead[0].StatusCode.ShouldNotBe(0u, "nonexistent PLC symbol must surface as a non-Good status");
|
||||
|
||||
// (3) Read-only declared tag — write must short-circuit with BadNotWritable before ADS.
|
||||
var roWrite = await drv.WriteAsync(
|
||||
[new WriteRequest("ReadOnlyCounter", 999)],
|
||||
TestContext.Current.CancellationToken);
|
||||
roWrite[0].StatusCode.ShouldBe(TwinCATStatusMapper.BadNotWritable);
|
||||
}
|
||||
|
||||
[TwinCATFact]
|
||||
public async Task Driver_routes_reads_per_device_and_isolates_unreachable_peers()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
|
||||
// Two devices in one driver: the real VM + a bogus AmsNetId that won't resolve. Tags
|
||||
// routed to the real device must still succeed; tags on the unreachable device must
|
||||
// surface comms errors without poisoning the healthy one — this is the multi-device
|
||||
// routing + per-device connection isolation contract the unit suite can't prove on the wire.
|
||||
var realHost = $"ads://{sim.TargetNetId}:{sim.AmsPort}";
|
||||
var ghostHost = "ads://99.99.99.99.1.1:851";
|
||||
var options = new TwinCATDriverOptions
|
||||
{
|
||||
Devices =
|
||||
[
|
||||
new TwinCATDeviceOptions(realHost, "Real-VM"),
|
||||
new TwinCATDeviceOptions(ghostHost, "Ghost-VM"),
|
||||
],
|
||||
Tags =
|
||||
[
|
||||
new TwinCATTagDefinition(
|
||||
Name: "RealCounter",
|
||||
DeviceHostAddress: realHost,
|
||||
SymbolPath: "GVL_Fixture.nCounter",
|
||||
DataType: TwinCATDataType.DInt),
|
||||
new TwinCATTagDefinition(
|
||||
Name: "GhostCounter",
|
||||
DeviceHostAddress: ghostHost,
|
||||
SymbolPath: "GVL_Fixture.nCounter",
|
||||
DataType: TwinCATDataType.DInt),
|
||||
],
|
||||
// Shorter timeout so the bogus device fails fast rather than dragging the whole
|
||||
// test; the healthy read shouldn't be slowed down by a peer timeout.
|
||||
Timeout = TimeSpan.FromSeconds(2),
|
||||
Probe = new TwinCATProbeOptions { Enabled = false },
|
||||
};
|
||||
await using var drv = new TwinCATDriver(options, driverInstanceId: "tc3-smoke-multidev");
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
var real = await drv.ReadAsync(["RealCounter"], TestContext.Current.CancellationToken);
|
||||
real[0].StatusCode.ShouldBe(0u, "healthy device read must succeed alongside unreachable peer");
|
||||
|
||||
var ghost = await drv.ReadAsync(["GhostCounter"], TestContext.Current.CancellationToken);
|
||||
ghost[0].StatusCode.ShouldNotBe(0u, "unreachable device read must surface non-Good status");
|
||||
|
||||
// Per-device host resolver — each tag's resolved host matches the device it was
|
||||
// declared against, regardless of the order reads arrive.
|
||||
drv.ResolveHost("RealCounter").ShouldBe(realHost);
|
||||
drv.ResolveHost("GhostCounter").ShouldBe(ghostHost);
|
||||
}
|
||||
|
||||
[TwinCATFact]
|
||||
public async Task Probe_loop_raises_host_status_transition_to_Running_on_reachable_target()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
|
||||
// Turn the probe loop on — InitializeAsync kicks off a background task per device
|
||||
// that calls AdsClient.ReadState. On first success the driver fires an
|
||||
// OnHostStatusChanged(Unknown|Stopped → Running). We only need to see one transition
|
||||
// to Running to prove the probe + event wiring is live.
|
||||
var options = new TwinCATDriverOptions
|
||||
{
|
||||
Devices = [new TwinCATDeviceOptions($"ads://{sim.TargetNetId}:{sim.AmsPort}", "XAR-VM")],
|
||||
Tags = [],
|
||||
Timeout = TimeSpan.FromSeconds(5),
|
||||
Probe = new TwinCATProbeOptions
|
||||
{
|
||||
Enabled = true,
|
||||
Interval = TimeSpan.FromMilliseconds(250),
|
||||
Timeout = TimeSpan.FromSeconds(2),
|
||||
},
|
||||
};
|
||||
await using var drv = new TwinCATDriver(options, driverInstanceId: "tc3-smoke-probe");
|
||||
|
||||
var runningSeen = new TaskCompletionSource<bool>();
|
||||
drv.OnHostStatusChanged += (_, e) =>
|
||||
{
|
||||
if (e.NewState == HostState.Running) runningSeen.TrySetResult(true);
|
||||
};
|
||||
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
// 5 s headroom: first probe fires ~250 ms after Initialize, plus ADS connect handshake.
|
||||
var completed = await Task.WhenAny(
|
||||
runningSeen.Task,
|
||||
Task.Delay(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken));
|
||||
completed.ShouldBe(runningSeen.Task, "probe loop must raise a Running transition within 5 s");
|
||||
|
||||
// Snapshot should also reflect Running — proves GetHostStatuses is in sync with the event.
|
||||
var statuses = drv.GetHostStatuses();
|
||||
statuses.Count.ShouldBe(1);
|
||||
statuses[0].State.ShouldBe(HostState.Running);
|
||||
}
|
||||
|
||||
[TwinCATFact]
|
||||
public async Task DiscoverAsync_renders_declared_tags_and_controller_browse_hits_address_space_builder()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
|
||||
// Hits the DiscoverAsync → IAddressSpaceBuilder pipeline the browse-only test bypasses.
|
||||
// With EnableControllerBrowse=true, the driver must (a) emit the pre-declared tag under
|
||||
// the device folder and (b) drop discovered symbols into a sibling "Discovered/" folder.
|
||||
var baseOptions = BuildOptions(sim);
|
||||
var options = new TwinCATDriverOptions
|
||||
{
|
||||
Devices = baseOptions.Devices,
|
||||
Tags = baseOptions.Tags,
|
||||
UseNativeNotifications = baseOptions.UseNativeNotifications,
|
||||
Timeout = baseOptions.Timeout,
|
||||
Probe = baseOptions.Probe,
|
||||
EnableControllerBrowse = true,
|
||||
};
|
||||
await using var drv = new TwinCATDriver(options, driverInstanceId: "tc3-smoke-discover");
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
var builder = new RecordingAddressSpaceBuilder();
|
||||
await drv.DiscoverAsync(builder, TestContext.Current.CancellationToken);
|
||||
|
||||
// Structural folders in the order the driver emits them: TwinCAT → device → Discovered.
|
||||
builder.FolderBrowseNames.ShouldContain("TwinCAT");
|
||||
builder.FolderBrowseNames.ShouldContain($"ads://{sim.TargetNetId}:{sim.AmsPort}");
|
||||
builder.FolderBrowseNames.ShouldContain("Discovered");
|
||||
|
||||
// Pre-declared tag from TwinCATDriverOptions.Tags — always emitted regardless of browse.
|
||||
builder.Variables.ShouldContain(v => v.BrowseName == "Counter"
|
||||
&& v.Info.DriverDataType == DriverDataType.Int32);
|
||||
|
||||
// Controller-discovered symbol — GVL_Fixture.nCounter lands under Discovered/.
|
||||
builder.Variables.ShouldContain(v => v.BrowseName == "GVL_Fixture.nCounter"
|
||||
&& v.Info.DriverDataType == DriverDataType.Int32);
|
||||
}
|
||||
|
||||
private static TwinCATDriverOptions BuildOptions(TwinCATXarFixture sim) => new()
|
||||
{
|
||||
Devices = [
|
||||
@@ -124,6 +561,12 @@ public sealed class TwinCAT3SmokeTests(TwinCATXarFixture sim)
|
||||
SymbolPath: "GVL_Fixture.rSetpoint",
|
||||
DataType: TwinCATDataType.Real,
|
||||
Writable: true),
|
||||
new TwinCATTagDefinition(
|
||||
Name: "ArrayElem",
|
||||
DeviceHostAddress: $"ads://{sim.TargetNetId}:{sim.AmsPort}",
|
||||
SymbolPath: "GVL_Arrays.aReal1D[5]",
|
||||
DataType: TwinCATDataType.Real,
|
||||
Writable: true),
|
||||
],
|
||||
UseNativeNotifications = true,
|
||||
Timeout = TimeSpan.FromSeconds(5),
|
||||
@@ -133,3 +576,42 @@ public sealed class TwinCAT3SmokeTests(TwinCATXarFixture sim)
|
||||
Probe = new TwinCATProbeOptions { Enabled = false },
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test double that captures every <see cref="IAddressSpaceBuilder.Folder"/> /
|
||||
/// <see cref="IAddressSpaceBuilder.Variable"/> call the driver makes during
|
||||
/// <c>DiscoverAsync</c>. Lets assertions inspect the resulting folder + variable tree
|
||||
/// without materializing an OPC UA node manager.
|
||||
/// </summary>
|
||||
internal sealed class RecordingAddressSpaceBuilder : IAddressSpaceBuilder
|
||||
{
|
||||
public List<(string BrowseName, string DisplayName)> Folders { get; } = [];
|
||||
public List<(string BrowseName, DriverAttributeInfo Info)> Variables { get; } = [];
|
||||
|
||||
public IEnumerable<string> FolderBrowseNames => Folders.Select(f => f.BrowseName);
|
||||
|
||||
public IAddressSpaceBuilder Folder(string browseName, string displayName)
|
||||
{
|
||||
Folders.Add((browseName, displayName));
|
||||
return this;
|
||||
}
|
||||
|
||||
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo info)
|
||||
{
|
||||
Variables.Add((browseName, info));
|
||||
return new Handle(info.FullName);
|
||||
}
|
||||
|
||||
public void AddProperty(string name, DriverDataType type, object? value) { }
|
||||
|
||||
private sealed class Handle(string fullRef) : IVariableHandle
|
||||
{
|
||||
public string FullReference => fullRef;
|
||||
public IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo info) => new NullSink();
|
||||
}
|
||||
|
||||
private sealed class NullSink : IAlarmConditionSink
|
||||
{
|
||||
public void OnTransition(AlarmEventArgs args) { }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="E_AxisState" Id="{ff675b51-fdf4-4a20-9755-d3a962aa226c}">
|
||||
<Declaration><![CDATA[TYPE E_AxisState :
|
||||
(
|
||||
Idle := 0,
|
||||
Homing := 1,
|
||||
Moving := 2,
|
||||
Stopped := 3,
|
||||
Faulted := 99
|
||||
) DINT;
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="E_Severity" Id="{00ec5016-5d26-4d67-bac9-3fc28b1c92ce}">
|
||||
<Declaration><![CDATA[TYPE E_Severity :
|
||||
(
|
||||
Info := 0,
|
||||
Warning := 1,
|
||||
Critical := 2,
|
||||
Fatal := 3
|
||||
) INT;
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_Alarm" Id="{d6459f8b-1fda-4bad-b787-c0e7e49fd8ec}">
|
||||
<Declaration><![CDATA[TYPE ST_Alarm :
|
||||
STRUCT
|
||||
Active : BOOL;
|
||||
Acknowledged : BOOL;
|
||||
Code : DINT;
|
||||
Severity : E_Severity;
|
||||
RaisedAt : DT;
|
||||
ClearedAt : DT;
|
||||
Message : STRING(80);
|
||||
Source : STRING(40);
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_Axis" Id="{2e150fb3-4694-4853-bb73-754d225c082a}">
|
||||
<Declaration><![CDATA[TYPE ST_Axis :
|
||||
STRUCT
|
||||
Name : STRING(32);
|
||||
State : E_AxisState;
|
||||
PositionMm : LREAL;
|
||||
VelocityMps : T_MeterPerSec;
|
||||
Accel : REAL;
|
||||
Motor : ST_Motor;
|
||||
Encoder : ST_Encoder;
|
||||
Commands : ST_AxisCommands;
|
||||
TravelLog : ARRAY[1..8] OF LREAL;
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_AxisCommands" Id="{0aaff3fd-5525-495b-9759-4de792f6e615}">
|
||||
<Declaration><![CDATA[TYPE ST_AxisCommands :
|
||||
STRUCT
|
||||
Enable : BOOL;
|
||||
Home : BOOL;
|
||||
Jog : BOOL;
|
||||
Stop : BOOL;
|
||||
TargetPos : LREAL;
|
||||
TargetVel : T_MeterPerSec;
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_Encoder" Id="{87f1e7c2-2359-4db5-acf3-46a1dd518acb}">
|
||||
<Declaration><![CDATA[TYPE ST_Encoder :
|
||||
STRUCT
|
||||
RawCounts : DINT;
|
||||
PositionMm : LREAL;
|
||||
VelocityMmPerS : T_MeterPerSec;
|
||||
Homed : BOOL;
|
||||
LastHomedAt : DT;
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_Line" Id="{3eaaae0a-31e2-43d6-b77c-5065a55c7d07}">
|
||||
<Declaration><![CDATA[TYPE ST_Line :
|
||||
STRUCT
|
||||
Name : STRING(32);
|
||||
Running : BOOL;
|
||||
Stations : ARRAY[1..3] OF ST_Station;
|
||||
Recipe : ST_Recipe;
|
||||
Stats : ST_Stats;
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_Motor" Id="{9354c15d-7882-42bb-8bce-017f74e49cca}">
|
||||
<Declaration><![CDATA[TYPE ST_Motor :
|
||||
STRUCT
|
||||
Current : REAL;
|
||||
Voltage : REAL;
|
||||
Temperature : T_Temperature;
|
||||
Rpm : DINT;
|
||||
Running : BOOL;
|
||||
Faulted : BOOL;
|
||||
SerialNo : STRING(24);
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_Recipe" Id="{723636a8-1265-46a5-88b3-fa1a3d77e594}">
|
||||
<Declaration><![CDATA[TYPE ST_Recipe :
|
||||
STRUCT
|
||||
Name : STRING(40);
|
||||
Description : WSTRING(120);
|
||||
Version : UINT;
|
||||
LoadedAt : DT;
|
||||
Steps : ARRAY[1..10] OF ST_RecipeStep;
|
||||
SupportedSkus: ARRAY[1..4] OF STRING(16);
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_RecipeStep" Id="{64d61cc8-2aba-4adb-9cf1-9345fc6f95b8}">
|
||||
<Declaration><![CDATA[TYPE ST_RecipeStep :
|
||||
STRUCT
|
||||
Enabled : BOOL;
|
||||
StepName : STRING(32);
|
||||
Duration : TIME;
|
||||
Setpoint : LREAL;
|
||||
Tolerance : REAL;
|
||||
Retries : USINT;
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_Station" Id="{ab0c22da-aee2-42de-be7f-05b8a8c27083}">
|
||||
<Declaration><![CDATA[TYPE ST_Station :
|
||||
STRUCT
|
||||
Name : STRING(32);
|
||||
Online : BOOL;
|
||||
Axes : ARRAY[1..4] OF ST_Axis;
|
||||
IO : ST_StationIO;
|
||||
Alarms : ARRAY[1..16] OF ST_Alarm;
|
||||
Heartbeat: UDINT;
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_StationIO" Id="{f71903d5-b9ea-4b75-9ca7-977b8374c11a}">
|
||||
<Declaration><![CDATA[TYPE ST_StationIO :
|
||||
STRUCT
|
||||
DigitalInputs : ARRAY[0..31] OF BOOL;
|
||||
DigitalOutputs : ARRAY[0..31] OF BOOL;
|
||||
AnalogInputs : ARRAY[0..7] OF REAL;
|
||||
AnalogOutputs : ARRAY[0..7] OF REAL;
|
||||
CycleCounter : UDINT;
|
||||
LastInputMask : DWORD;
|
||||
LastOutputMask : DWORD;
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="ST_Stats" Id="{23dffb59-ae06-4ac7-8c98-cba78dddf81d}">
|
||||
<Declaration><![CDATA[TYPE ST_Stats :
|
||||
STRUCT
|
||||
UnitsProduced : UDINT;
|
||||
UnitsRejected : UDINT;
|
||||
UpTimeSeconds : UDINT;
|
||||
LastRejectAt : DT;
|
||||
LastProducedAt : DT;
|
||||
RejectReasons : ARRAY[1..5] OF UDINT;
|
||||
END_STRUCT
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="T_MeterPerSec" Id="{bddf08a2-da6c-4076-9719-13806a9e2438}">
|
||||
<Declaration><![CDATA[TYPE T_MeterPerSec : LREAL;
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<DUT Name="T_Temperature" Id="{5e81fac6-ab58-4311-b798-907495f9ead9}">
|
||||
<Declaration><![CDATA[TYPE T_Temperature : LREAL;
|
||||
END_TYPE
|
||||
]]></Declaration>
|
||||
</DUT>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<GVL Name="GVL_Arrays" Id="{6d45cf94-641a-40eb-a780-4fb3a1f8984f}">
|
||||
<Declaration><![CDATA[{attribute 'qualified_only'}
|
||||
VAR_GLOBAL
|
||||
// 1-D arrays of primitives.
|
||||
aBool1D : ARRAY[0..9] OF BOOL;
|
||||
aInt1D : ARRAY[0..9] OF INT := [10(0)];
|
||||
aDInt1D : ARRAY[1..16] OF DINT;
|
||||
aReal1D : ARRAY[0..31] OF REAL;
|
||||
aLReal1D : ARRAY[0..7] OF LREAL;
|
||||
aString1D : ARRAY[1..4] OF STRING(32);
|
||||
|
||||
// 2-D and 3-D arrays.
|
||||
aReal2D : ARRAY[1..4, 1..4] OF REAL;
|
||||
aDInt3D : ARRAY[0..2, 0..2, 0..2] OF DINT;
|
||||
|
||||
// Array-of-UDT (exercises per-element browse of nested structs).
|
||||
aAxisSnapshots : ARRAY[1..4] OF ST_Axis;
|
||||
END_VAR
|
||||
]]></Declaration>
|
||||
</GVL>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<GVL Name="GVL_Enums" Id="{a0e45f27-3675-4b6f-bc09-ded0723b7029}">
|
||||
<Declaration><![CDATA[{attribute 'qualified_only'}
|
||||
VAR_GLOBAL
|
||||
// Enum + alias coverage — standalone globals so OPC UA browse can assert
|
||||
// on EnumStrings / DataTypeDefinition rendering without walking into the
|
||||
// plant hierarchy.
|
||||
currentAxisState : E_AxisState := E_AxisState.Idle;
|
||||
currentSeverity : E_Severity := E_Severity.Info;
|
||||
severityLog : ARRAY[1..8] OF E_Severity;
|
||||
cabinetTemperature : T_Temperature := 22.5;
|
||||
conveyorSpeed : T_MeterPerSec := 1.5;
|
||||
END_VAR
|
||||
]]></Declaration>
|
||||
</GVL>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<GVL Name="GVL_Fixture" Id="{cdbd99aa-f3c6-48ad-a068-d31a9e1a3b21}">
|
||||
<Declaration><![CDATA[{attribute 'qualified_only'}
|
||||
VAR_GLOBAL
|
||||
// Monotonic counter — MAIN increments every cycle. Seed 1234 is the
|
||||
// floor the smoke tests assert against.
|
||||
nCounter : DINT := 1234;
|
||||
|
||||
// Scratch REAL for write-then-read round-trip.
|
||||
rSetpoint : REAL := 0.0;
|
||||
|
||||
// Reserved for discovery / browse tests.
|
||||
bFlag : BOOL := TRUE;
|
||||
END_VAR
|
||||
]]></Declaration>
|
||||
</GVL>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<GVL Name="GVL_Plant" Id="{00c8ed35-95d3-494a-92d8-db5f2c8ab6d9}">
|
||||
<Declaration><![CDATA[{attribute 'qualified_only'}
|
||||
VAR_GLOBAL
|
||||
// Top-level plant hierarchy exposed to OPC UA browse:
|
||||
// GVL_Plant.Line1.Stations[1..3].Axes[1..4].Motor/Encoder/Commands
|
||||
// .IO
|
||||
// .Alarms[1..16]
|
||||
// .Recipe.Steps[1..10]
|
||||
// .Stats
|
||||
Line1 : ST_Line := (
|
||||
Name := 'Assembly-01',
|
||||
Running := TRUE
|
||||
);
|
||||
END_VAR
|
||||
]]></Declaration>
|
||||
</GVL>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<GVL Name="GVL_Primitives" Id="{2f721507-9717-45cf-bf40-02a9691bb5b4}">
|
||||
<Declaration><![CDATA[{attribute 'qualified_only'}
|
||||
VAR_GLOBAL
|
||||
// One of every primitive ADS type. Exercises the full
|
||||
// TwinCATDataType → OPC UA NodeId mapping.
|
||||
vBool : BOOL := TRUE;
|
||||
vByte : BYTE := 16#A5;
|
||||
vWord : WORD := 16#BEEF;
|
||||
vDWord : DWORD := 16#DEADBEEF;
|
||||
vLWord : LWORD := 16#0123456789ABCDEF;
|
||||
vSInt : SINT := -42;
|
||||
vUSInt : USINT := 250;
|
||||
vInt : INT := -12345;
|
||||
vUInt : UINT := 54321;
|
||||
vDInt : DINT := -1234567;
|
||||
vUDInt : UDINT := 4000000000;
|
||||
vLInt : LINT := -1234567890123;
|
||||
vULInt : ULINT := 12345678901234567;
|
||||
vReal : REAL := 3.14159;
|
||||
vLReal : LREAL := 2.7182818284590452;
|
||||
vString : STRING(80) := 'Hello from TC3';
|
||||
vWString : WSTRING(80) := "unicode ✓";
|
||||
vTime : TIME := T#2h34m17s500ms;
|
||||
vTimeOfDay : TOD := TOD#08:30:00;
|
||||
vDate : DATE := D#2026-04-22;
|
||||
vDateTime : DT := DT#2026-04-22-08:30:00;
|
||||
END_VAR
|
||||
]]></Declaration>
|
||||
</GVL>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,54 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<POU Name="FB_AxisSim" Id="{5b3e4e46-5ace-4e6c-a0dc-d55113a89212}" SpecialFunc="None">
|
||||
<Declaration><![CDATA[FUNCTION_BLOCK FB_AxisSim
|
||||
VAR_INPUT
|
||||
Enable : BOOL;
|
||||
END_VAR
|
||||
VAR_IN_OUT
|
||||
Axis : ST_Axis;
|
||||
END_VAR
|
||||
VAR
|
||||
tick : UDINT;
|
||||
END_VAR
|
||||
]]></Declaration>
|
||||
<Implementation>
|
||||
<ST><![CDATA[IF NOT Enable THEN
|
||||
Axis.State := E_AxisState.Idle;
|
||||
RETURN;
|
||||
END_IF
|
||||
|
||||
tick := tick + 1;
|
||||
|
||||
// Ramp position + derive velocity so a subscription sees LREAL churn.
|
||||
Axis.PositionMm := Axis.PositionMm + 0.5;
|
||||
Axis.VelocityMps := 0.5 * SIN(UDINT_TO_LREAL(tick) * 0.05);
|
||||
Axis.Accel := LREAL_TO_REAL(0.1 * COS(UDINT_TO_LREAL(tick) * 0.05));
|
||||
Axis.State := E_AxisState.Moving;
|
||||
|
||||
// Motor block — keep values sane but moving.
|
||||
Axis.Motor.Current := 2.5 + LREAL_TO_REAL(0.5 * SIN(UDINT_TO_LREAL(tick) * 0.1));
|
||||
Axis.Motor.Voltage := 24.0;
|
||||
Axis.Motor.Temperature:= 35.0 + 5.0 * SIN(UDINT_TO_LREAL(tick) * 0.01);
|
||||
Axis.Motor.Rpm := 1500 + LREAL_TO_DINT(200.0 * SIN(UDINT_TO_LREAL(tick) * 0.05));
|
||||
Axis.Motor.Running := TRUE;
|
||||
|
||||
// Encoder
|
||||
Axis.Encoder.RawCounts := Axis.Encoder.RawCounts + 12;
|
||||
Axis.Encoder.PositionMm := Axis.PositionMm;
|
||||
Axis.Encoder.VelocityMmPerS := Axis.VelocityMps;
|
||||
Axis.Encoder.Homed := TRUE;
|
||||
|
||||
// Travel log — rolling window of last 8 positions.
|
||||
Axis.TravelLog[1] := Axis.TravelLog[2];
|
||||
Axis.TravelLog[2] := Axis.TravelLog[3];
|
||||
Axis.TravelLog[3] := Axis.TravelLog[4];
|
||||
Axis.TravelLog[4] := Axis.TravelLog[5];
|
||||
Axis.TravelLog[5] := Axis.TravelLog[6];
|
||||
Axis.TravelLog[6] := Axis.TravelLog[7];
|
||||
Axis.TravelLog[7] := Axis.TravelLog[8];
|
||||
Axis.TravelLog[8] := Axis.PositionMm;
|
||||
]]></ST>
|
||||
</Implementation>
|
||||
</POU>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,66 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<POU Name="FB_LineSim" Id="{83bd0d62-650e-4191-9410-a31c2eb07c02}" SpecialFunc="None">
|
||||
<Declaration><![CDATA[FUNCTION_BLOCK FB_LineSim
|
||||
VAR_IN_OUT
|
||||
Line : ST_Line;
|
||||
END_VAR
|
||||
VAR
|
||||
tick : UDINT;
|
||||
axisSim : ARRAY[1..3, 1..4] OF FB_AxisSim;
|
||||
iStation : INT;
|
||||
iAxis : INT;
|
||||
iAlarm : INT;
|
||||
rotatorBits : DWORD;
|
||||
END_VAR
|
||||
]]></Declaration>
|
||||
<Implementation>
|
||||
<ST><![CDATA[tick := tick + 1;
|
||||
|
||||
FOR iStation := 1 TO 3 DO
|
||||
Line.Stations[iStation].Online := TRUE;
|
||||
Line.Stations[iStation].Heartbeat := tick;
|
||||
|
||||
// Axes — delegate to FB_AxisSim for per-cycle motion.
|
||||
FOR iAxis := 1 TO 4 DO
|
||||
axisSim[iStation, iAxis](
|
||||
Enable := Line.Running,
|
||||
Axis := Line.Stations[iStation].Axes[iAxis]
|
||||
);
|
||||
END_FOR
|
||||
|
||||
// Rolling I/O patterns to give subscribers something to watch.
|
||||
rotatorBits := SHL(DWORD#1, (tick MOD 32));
|
||||
Line.Stations[iStation].IO.LastInputMask := rotatorBits;
|
||||
Line.Stations[iStation].IO.LastOutputMask := NOT rotatorBits;
|
||||
Line.Stations[iStation].IO.CycleCounter := tick;
|
||||
|
||||
// Flip a couple of DI/DOs so BOOL arrays see changes.
|
||||
Line.Stations[iStation].IO.DigitalInputs[(tick MOD 32)] := NOT Line.Stations[iStation].IO.DigitalInputs[(tick MOD 32)];
|
||||
Line.Stations[iStation].IO.DigitalOutputs[(tick MOD 32)] := Line.Stations[iStation].IO.DigitalInputs[(tick MOD 32)];
|
||||
|
||||
// Walk an analog channel through a sine.
|
||||
Line.Stations[iStation].IO.AnalogInputs[0] := LREAL_TO_REAL(10.0 + 5.0 * SIN(UDINT_TO_LREAL(tick + UDINT#100 * UINT_TO_UDINT(INT_TO_UINT(iStation))) * 0.05));
|
||||
Line.Stations[iStation].IO.AnalogOutputs[0] := Line.Stations[iStation].IO.AnalogInputs[0] * 2.0;
|
||||
|
||||
// Rotate one alarm per station so IAlarmSource has state transitions.
|
||||
iAlarm := INT_TO_USINT(1 + (DINT_TO_INT(UDINT_TO_DINT(tick)) MOD 16));
|
||||
Line.Stations[iStation].Alarms[iAlarm].Active := (tick MOD 32) >= 16;
|
||||
Line.Stations[iStation].Alarms[iAlarm].Severity := E_Severity.Warning;
|
||||
Line.Stations[iStation].Alarms[iAlarm].Code := 1000 + DINT(iAlarm);
|
||||
Line.Stations[iStation].Alarms[iAlarm].Message := CONCAT('alarm-', TO_STRING(iAlarm));
|
||||
Line.Stations[iStation].Alarms[iAlarm].Source := CONCAT('Station-', TO_STRING(iStation));
|
||||
END_FOR
|
||||
|
||||
// Stats — monotonic production counters.
|
||||
Line.Stats.UnitsProduced := Line.Stats.UnitsProduced + 1;
|
||||
IF (tick MOD 100) = 0 THEN
|
||||
Line.Stats.UnitsRejected := Line.Stats.UnitsRejected + 1;
|
||||
Line.Stats.RejectReasons[1 + ((DINT_TO_INT(UDINT_TO_DINT(tick / 100))) MOD 5)] :=
|
||||
Line.Stats.RejectReasons[1 + ((DINT_TO_INT(UDINT_TO_DINT(tick / 100))) MOD 5)] + 1;
|
||||
END_IF
|
||||
Line.Stats.UpTimeSeconds := tick / 100; // 10 ms task tick -> approx seconds
|
||||
]]></ST>
|
||||
</Implementation>
|
||||
</POU>
|
||||
</TcPlcObject>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TcPlcObject Version="1.1.0.1" ProductVersion="3.1.4024.0">
|
||||
<POU Name="MAIN" Id="{eaceb1e4-5544-4368-a12f-3e05dd0be17a}" SpecialFunc="None">
|
||||
<Declaration><![CDATA[PROGRAM MAIN
|
||||
VAR
|
||||
lineSim : FB_LineSim;
|
||||
i : INT;
|
||||
j : INT;
|
||||
k : INT;
|
||||
END_VAR
|
||||
]]></Declaration>
|
||||
<Implementation>
|
||||
<ST><![CDATA[// Smoke-test contract: monotonic counter on GVL_Fixture.nCounter.
|
||||
// See TwinCAT3SmokeTests.cs (Driver_reads_seeded_DINT_through_real_ADS +
|
||||
// Driver_subscribe_receives_native_ADS_notifications_on_counter_changes).
|
||||
GVL_Fixture.nCounter := GVL_Fixture.nCounter + 1;
|
||||
|
||||
// Drive the complex fixture.
|
||||
lineSim(Line := GVL_Plant.Line1);
|
||||
|
||||
// Keep the standalone enum / alias globals churning so browse + subscribe
|
||||
// tests against GVL_Enums see changes without reaching into GVL_Plant.
|
||||
IF (GVL_Fixture.nCounter MOD 10) = 0 THEN
|
||||
GVL_Enums.currentAxisState := GVL_Plant.Line1.Stations[1].Axes[1].State;
|
||||
GVL_Enums.currentSeverity := E_Severity.Info;
|
||||
GVL_Enums.cabinetTemperature := GVL_Plant.Line1.Stations[1].Axes[1].Motor.Temperature;
|
||||
GVL_Enums.conveyorSpeed := GVL_Plant.Line1.Stations[1].Axes[1].VelocityMps;
|
||||
END_IF
|
||||
|
||||
// Stir a 2-D / 3-D array entry so multi-rank subscribes see value churn.
|
||||
i := 1 + (GVL_Fixture.nCounter MOD 4);
|
||||
j := 1 + ((GVL_Fixture.nCounter / 4) MOD 4);
|
||||
GVL_Arrays.aReal2D[i, j] := LREAL_TO_REAL(SIN(DINT_TO_LREAL(GVL_Fixture.nCounter) * 0.01));
|
||||
|
||||
k := GVL_Fixture.nCounter MOD 3;
|
||||
GVL_Arrays.aDInt3D[k, k, k] := GVL_Fixture.nCounter;
|
||||
|
||||
GVL_Arrays.aInt1D[GVL_Fixture.nCounter MOD 10] := DINT_TO_INT(GVL_Fixture.nCounter MOD 10000);
|
||||
]]></ST>
|
||||
</Implementation>
|
||||
</POU>
|
||||
</TcPlcObject>
|
||||
@@ -1,12 +1,15 @@
|
||||
# TwinCAT XAR fixture project
|
||||
|
||||
This folder holds the TwinCAT 3 XAE project that the XAR VM runs for the
|
||||
integration-tests suite (`tests/.../TwinCAT.IntegrationTests/*.cs`).
|
||||
This folder holds the TwinCAT 3 XAE project that the XAR VM (or TCBSD
|
||||
target) runs for the integration-tests suite and the broader browse /
|
||||
UDT / array / enum coverage exercised by the OPC UA driver.
|
||||
|
||||
**Status today**: stub. The `.tsproj` isn't committed yet; once the XAR
|
||||
VM is up + a project with the required state exists, export via
|
||||
File → Export + drop it here as `OtOpcUaTwinCatFixture.tsproj` + its
|
||||
PLC `.library` / `.plcproj` companions.
|
||||
**Status today**: the `.sln` / `.tsproj` / `.plcproj` wrappers still get
|
||||
generated per-workstation in XAE (GUIDs are install-specific), but every
|
||||
PLC object is committed as a standalone `.TcGVL` / `.TcDUT` / `.TcPOU`
|
||||
under `PLC/{GVLs,DUTs,POUs}/`. Reconstruction is "Add Existing Item" of
|
||||
each file into a fresh XAE project — see **Importing the committed PLC
|
||||
objects** below.
|
||||
|
||||
## Why `.tsproj`, not the binary bootproject
|
||||
|
||||
@@ -30,41 +33,89 @@ Reconstruction workflow on the VM:
|
||||
|
||||
## Required project state
|
||||
|
||||
The smoke tests in `TwinCAT3SmokeTests.cs` depend on this exact GVL +
|
||||
PLC setup. Missing or renamed symbols surface as ADS `DeviceSymbolNotFound`
|
||||
or wrong-type read failures, not silent skips.
|
||||
`TwinCAT3SmokeTests.cs` ships 14 `[TwinCATFact]` methods plus a 16-case
|
||||
`[TwinCATTheory]` — the tests depend on the exact shapes below. Missing
|
||||
or renamed symbols surface as ADS `DeviceSymbolNotFound` or wrong-type
|
||||
read failures, not silent skips. Changed seed values will flip specific
|
||||
assertions — the load-bearing ones are called out inline.
|
||||
|
||||
### Global Variable List: `GVL_Fixture`
|
||||
### Integration-test contract
|
||||
|
||||
```st
|
||||
VAR_GLOBAL
|
||||
// Monotonically-increasing counter; MAIN increments each cycle.
|
||||
// Seed value 1234 picked so the smoke test can assert ">= 1234" without
|
||||
// synchronising with the initial cycle.
|
||||
nCounter : DINT := 1234;
|
||||
The dependency surface spans `GVL_Fixture`, `GVL_Primitives`, `GVL_Arrays`,
|
||||
`GVL_Enums`, `GVL_Plant`, and `MAIN`.
|
||||
|
||||
// Scratch REAL for write-then-read round-trip test. Smoke test writes
|
||||
// 42.5 + reads back.
|
||||
rSetpoint : REAL := 0.0;
|
||||
**`GVL_Fixture`** (source: [`PLC/GVLs/GVL_Fixture.TcGVL`](PLC/GVLs/GVL_Fixture.TcGVL))
|
||||
holds exactly three variables — `nCounter : DINT := 1234`,
|
||||
`rSetpoint : REAL := 0.0`, `bFlag : BOOL := TRUE`. `MAIN`
|
||||
(source: [`PLC/POUs/MAIN.TcPOU`](PLC/POUs/MAIN.TcPOU)) increments
|
||||
`nCounter` every cycle so the native-notification test sees monotonic
|
||||
change without writing. Seeded values aren't reliable — PlcTask
|
||||
watchdog restarts reset them — so the read test only asserts a
|
||||
non-negative DINT.
|
||||
|
||||
// Readable boolean with seed value TRUE. Reserved for future
|
||||
// expansion (e.g. discovery / symbol-browse tests).
|
||||
bFlag : BOOL := TRUE;
|
||||
END_VAR
|
||||
**`GVL_Primitives.vWord := 16#BEEF`** — the bit-indexed BOOL test pins
|
||||
to bit 3 (set in `0xBEEF`) and bit 4 (clear). Changing the seed flips
|
||||
that test.
|
||||
|
||||
**`GVL_Primitives` numeric seeds** — the primitive-type theory reads
|
||||
each of `vSInt, vUSInt, vInt, vUInt, vDInt, vUDInt, vLInt, vULInt,
|
||||
vReal, vLReal, vString` and asserts the exact seed value. Matches
|
||||
the declarations in [`PLC/GVLs/GVL_Primitives.TcGVL`](PLC/GVLs/GVL_Primitives.TcGVL).
|
||||
|
||||
**`GVL_Arrays.aReal1D[5]`** — the array round-trip test writes + reads
|
||||
element index 5. The array must be writable; don't apply read-only
|
||||
attributes.
|
||||
|
||||
**`GVL_Plant.Line1.Stations[1].Axes[1].Motor.{Temperature, Running}`** —
|
||||
the nested-UDT test reads both (LREAL + BOOL). `FB_LineSim` must be
|
||||
driving the hierarchy (see `MAIN`) so values are alive.
|
||||
|
||||
**`GVL_Enums.currentAxisState`** — the browse test asserts this symbol
|
||||
surfaces by name.
|
||||
|
||||
### Complex hierarchy (for browse / UDT / array / enum coverage)
|
||||
|
||||
All sources in [`PLC/`](PLC/). Commits are split
|
||||
one-object-per-file so XAE can "Add Existing Item" each into a fresh
|
||||
project (the `.plcproj` wrapper is environment-specific and not
|
||||
committed).
|
||||
|
||||
**Type coverage** — `GVL_Primitives` has one of every ADS primitive:
|
||||
`BOOL, BYTE, WORD, DWORD, LWORD, SINT, USINT, INT, UINT, DINT, UDINT,
|
||||
LINT, ULINT, REAL, LREAL, STRING(80), WSTRING(80), TIME, TOD, DATE, DT`.
|
||||
|
||||
**Array coverage** — `GVL_Arrays` has 1-D primitives, `ARRAY[1..4,1..4]
|
||||
OF REAL`, `ARRAY[0..2,0..2,0..2] OF DINT`, plus `ARRAY[1..4] OF ST_Axis`
|
||||
for per-element nested-struct browse.
|
||||
|
||||
**Enum + alias coverage** — `E_AxisState : DINT`, `E_Severity : INT`,
|
||||
`T_Temperature : LREAL`, `T_MeterPerSec : LREAL`. `GVL_Enums` exposes
|
||||
each at the root so tests can assert `EnumStrings` /
|
||||
`DataTypeDefinition` rendering without walking the plant hierarchy.
|
||||
|
||||
**5-level plant hierarchy** — rooted at `GVL_Plant.Line1 : ST_Line`:
|
||||
|
||||
```
|
||||
GVL_Plant.Line1 (ST_Line)
|
||||
.Stations[1..3] (ARRAY OF ST_Station)
|
||||
.Axes[1..4] (ARRAY OF ST_Axis)
|
||||
.Motor (ST_Motor)
|
||||
.Encoder (ST_Encoder)
|
||||
.Commands (ST_AxisCommands)
|
||||
.TravelLog[1..8] (ARRAY OF LREAL)
|
||||
.IO (ST_StationIO — 32x DI/DO, 8x AI/AO)
|
||||
.Alarms[1..16] (ARRAY OF ST_Alarm)
|
||||
.Recipe (ST_Recipe)
|
||||
.Steps[1..10] (ARRAY OF ST_RecipeStep)
|
||||
.SupportedSkus[1..4] (ARRAY OF STRING)
|
||||
.Stats (ST_Stats)
|
||||
```
|
||||
|
||||
### PLC program: `MAIN`
|
||||
|
||||
```st
|
||||
PROGRAM MAIN
|
||||
VAR
|
||||
END_VAR
|
||||
|
||||
// One-line program: increment the fixture counter every cycle.
|
||||
// The native-notification smoke test subscribes to GVL_Fixture.nCounter
|
||||
// + observes the monotonic changes without a write path.
|
||||
GVL_Fixture.nCounter := GVL_Fixture.nCounter + 1;
|
||||
```
|
||||
**Live value churn** — `FB_LineSim` + `FB_AxisSim` are called from
|
||||
`MAIN` every cycle: axes ramp position + derive velocity/accel, motor
|
||||
current/temperature track a sine, IO masks rotate, one alarm per station
|
||||
toggles each 32 cycles, stats counters increment. Subscription tests
|
||||
see real data-change notifications without an external writer.
|
||||
|
||||
### Task
|
||||
|
||||
@@ -77,6 +128,30 @@ GVL_Fixture.nCounter := GVL_Fixture.nCounter + 1;
|
||||
to this. Use runtime 2 / port `852` only if the single runtime is
|
||||
already taken by another project on the same VM.
|
||||
|
||||
## Importing the committed PLC objects
|
||||
|
||||
On a machine with a working TcXaeShell (or Visual Studio with the TC3
|
||||
XAE integration):
|
||||
|
||||
1. File → New → Project → **TwinCAT XAE Project** → name
|
||||
`OtOpcUaTwinCatFixture`. This lays down the `.sln` + `.tsproj`
|
||||
scaffolding.
|
||||
2. In the Solution Explorer, right-click the `PLC` node →
|
||||
**Add New Item → Standard PLC Project** → name `PLC`. Delete the
|
||||
auto-generated stub `MAIN` — the committed one will replace it.
|
||||
3. Right-click the PLC project's `DUTs` folder → **Add → Existing Item
|
||||
…** → multi-select every file under [`PLC/DUTs/`](PLC/DUTs/) and
|
||||
**Add As Link** (so the repo stays the source of truth). Repeat for
|
||||
`GVLs/` → [`PLC/GVLs/`](PLC/GVLs/) and `POUs/` →
|
||||
[`PLC/POUs/`](PLC/POUs/).
|
||||
4. Assign `MAIN` to `PlcTask` (cyclic, 10 ms, priority 20).
|
||||
5. Set the target system to the TCBSD / XAR VM via the AMS route, then
|
||||
**Build → Build Solution** + **Activate Configuration → Run Mode**.
|
||||
|
||||
If XAE complains about missing references while importing, add the DUTs
|
||||
before the GVLs (the structs are referenced by the plant GVL) and the
|
||||
enums/aliases first within DUTs.
|
||||
|
||||
## XAR VM setup (one-time)
|
||||
|
||||
Full bootstrap lives in `docs/v2/dev-environment.md`. The TwinCAT-specific
|
||||
@@ -126,14 +201,17 @@ Options to eliminate the manual step:
|
||||
On the dev box:
|
||||
|
||||
```powershell
|
||||
$env:TWINCAT_TARGET_HOST = '10.0.0.42' # replace with the VM IP
|
||||
$env:TWINCAT_TARGET_NETID = '5.23.91.23.1.1' # replace with the VM AmsNetId
|
||||
# $env:TWINCAT_TARGET_PORT = '852' # only if not using PLC runtime 1
|
||||
$env:TWINCAT_TARGET_NETID = '5.23.91.23.1.1' # replace with the VM AmsNetId — REQUIRED
|
||||
$env:TWINCAT_TARGET_HOST = '10.0.0.42' # replace with the VM IP (defaults to localhost)
|
||||
# $env:TWINCAT_TARGET_PORT = '852' # only if not using PLC runtime 1 (default 851)
|
||||
dotnet test tests\ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.IntegrationTests
|
||||
```
|
||||
|
||||
With any of those env vars unset, all three smoke tests skip cleanly via
|
||||
`[TwinCATFact]`; unit suite (`TwinCAT.Tests`) runs unchanged.
|
||||
Only `TWINCAT_TARGET_NETID` is required — fixture gates on it specifically.
|
||||
`TWINCAT_TARGET_HOST` defaults to `localhost` when unset; `TWINCAT_TARGET_PORT`
|
||||
defaults to `851`. With the NetID unset, the whole integration suite
|
||||
(~28 cases, both `[TwinCATFact]` and `[TwinCATTheory]`) skips cleanly;
|
||||
unit suite (`TwinCAT.Tests`) runs unchanged.
|
||||
|
||||
## See also
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
using System.Reflection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Server;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Server.Redundancy;
|
||||
using ConfigRedundancyMode = ZB.MOM.WW.OtOpcUa.Configuration.Enums.RedundancyMode;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Server.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Unit coverage for <see cref="ServerRedundancyNodeWriter"/>. Uses a <see cref="DispatchProxy"/>
|
||||
/// stand-in for <see cref="IServerInternal"/> — the writer only needs <c>ServerObject</c> +
|
||||
/// <c>DefaultSystemContext</c>, so we stub just those and let every other member return
|
||||
/// null (the writer never touches anything else).
|
||||
/// </summary>
|
||||
public sealed class ServerRedundancyNodeWriterTests
|
||||
{
|
||||
[Fact]
|
||||
public void ApplyServiceLevel_sets_node_value_and_dedupes_unchanged()
|
||||
{
|
||||
var env = BuildEnv();
|
||||
|
||||
env.Writer.ApplyServiceLevel(200);
|
||||
env.ServerObject.ServiceLevel.Value.ShouldBe((byte)200);
|
||||
|
||||
var timestampAfterFirst = env.ServerObject.ServiceLevel.Timestamp;
|
||||
|
||||
// Same value — writer should early-out without touching Timestamp.
|
||||
Thread.Sleep(5);
|
||||
env.Writer.ApplyServiceLevel(200);
|
||||
env.ServerObject.ServiceLevel.Timestamp.ShouldBe(timestampAfterFirst);
|
||||
|
||||
env.Writer.ApplyServiceLevel(150);
|
||||
env.ServerObject.ServiceLevel.Value.ShouldBe((byte)150);
|
||||
env.ServerObject.ServiceLevel.Timestamp.ShouldBeGreaterThan(timestampAfterFirst);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyRedundancySupport_maps_config_enum()
|
||||
{
|
||||
var env = BuildEnv();
|
||||
|
||||
env.Writer.ApplyRedundancySupport(ConfigRedundancyMode.Warm);
|
||||
env.ServerObject.ServerRedundancy.RedundancySupport.Value.ShouldBe(RedundancySupport.Warm);
|
||||
|
||||
env.Writer.ApplyRedundancySupport(ConfigRedundancyMode.Hot);
|
||||
env.ServerObject.ServerRedundancy.RedundancySupport.Value.ShouldBe(RedundancySupport.Hot);
|
||||
|
||||
env.Writer.ApplyRedundancySupport(ConfigRedundancyMode.None);
|
||||
env.ServerObject.ServerRedundancy.RedundancySupport.Value.ShouldBe(RedundancySupport.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyServerUriArray_writes_when_non_transparent_state_present()
|
||||
{
|
||||
var env = BuildEnv(nonTransparent: true);
|
||||
|
||||
env.Writer.ApplyServerUriArray(["urn:self", "urn:peer"]);
|
||||
var ntr = (NonTransparentRedundancyState)env.ServerObject.ServerRedundancy;
|
||||
ntr.ServerUriArray.Value.ShouldBe(new[] { "urn:self", "urn:peer" });
|
||||
|
||||
var ts = ntr.ServerUriArray.Timestamp;
|
||||
Thread.Sleep(5);
|
||||
env.Writer.ApplyServerUriArray(["urn:self", "urn:peer"]); // dedupe
|
||||
ntr.ServerUriArray.Timestamp.ShouldBe(ts);
|
||||
|
||||
env.Writer.ApplyServerUriArray(["urn:self", "urn:peer", "urn:peer2"]);
|
||||
ntr.ServerUriArray.Value.Length.ShouldBe(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyServerUriArray_skips_silently_on_base_redundancy_type()
|
||||
{
|
||||
var env = BuildEnv(nonTransparent: false);
|
||||
Should.NotThrow(() => env.Writer.ApplyServerUriArray(["urn:self"]));
|
||||
env.ServerObject.ServerRedundancy.ShouldBeOfType<ServerRedundancyState>();
|
||||
}
|
||||
|
||||
private static Env BuildEnv(bool nonTransparent = false)
|
||||
{
|
||||
var serverObject = new ServerObjectState(parent: null)
|
||||
{
|
||||
ServiceLevel = new PropertyState<byte>(null),
|
||||
};
|
||||
serverObject.ServerRedundancy = nonTransparent
|
||||
? new NonTransparentRedundancyState(serverObject)
|
||||
{
|
||||
RedundancySupport = new PropertyState<RedundancySupport>(null),
|
||||
ServerUriArray = new PropertyState<string[]>(null),
|
||||
}
|
||||
: new ServerRedundancyState(serverObject)
|
||||
{
|
||||
RedundancySupport = new PropertyState<RedundancySupport>(null),
|
||||
};
|
||||
|
||||
var proxy = DispatchProxy.Create<IServerInternal, FakeServerInternalProxy>();
|
||||
var fake = (FakeServerInternalProxy)(object)proxy;
|
||||
fake.ServerObjectValue = serverObject;
|
||||
fake.DefaultSystemContextValue = new ServerSystemContext(proxy);
|
||||
|
||||
var writer = new ServerRedundancyNodeWriter(proxy, NullLogger<ServerRedundancyNodeWriter>.Instance);
|
||||
return new Env(proxy, serverObject, writer);
|
||||
}
|
||||
|
||||
private sealed record Env(
|
||||
IServerInternal Server,
|
||||
ServerObjectState ServerObject,
|
||||
ServerRedundancyNodeWriter Writer);
|
||||
|
||||
public class FakeServerInternalProxy : DispatchProxy
|
||||
{
|
||||
public ServerObjectState? ServerObjectValue;
|
||||
public ISystemContext? DefaultSystemContextValue;
|
||||
|
||||
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) =>
|
||||
targetMethod?.Name switch
|
||||
{
|
||||
"get_ServerObject" => ServerObjectValue,
|
||||
"get_DefaultSystemContext" => DefaultSystemContextValue,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@
|
||||
<PackageReference Include="xunit.v3" Version="1.1.0"/>
|
||||
<PackageReference Include="Shouldly" Version="4.3.0"/>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0"/>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0"/>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.3"/>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.0"/>
|
||||
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client" Version="1.5.374.126"/>
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.2">
|
||||
|
||||
Reference in New Issue
Block a user