diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATDriver.cs
index 8542bcad1..fc0469ae8 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATDriver.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATDriver.cs
@@ -11,7 +11,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT;
/// the skeleton; read / write / discover / subscribe / probe / host-
/// resolver land in PRs 2 and 3.
///
-public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery, ISubscribable,
+public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery, IBatchSubscribable,
IHostConnectivityProbe, IPerCallHostResolver, IRediscoverable, ISkippedTagReporter, IDriverDiagnostics,
IDisposable, IAsyncDisposable
{
@@ -88,6 +88,12 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
/// Occurs when a subscribed tag value changes.
public event EventHandler? OnDataChange;
+ ///
+ /// Batched data changes (R02:P1): one raise per poll cycle on the poll path, one per notification on
+ /// the native path (each ADS notification is its own burst). DriverInstanceActor subscribes only this
+ /// event of a batch-capable driver, so EVERY data change the driver publishes goes through both.
+ ///
+ public event EventHandler? OnDataChangeBatch;
/// Occurs when a device host connectivity status changes.
public event EventHandler? OnHostStatusChanged;
/// Occurs when the Galaxy object hierarchy or TwinCAT symbol table is rediscovered.
@@ -115,6 +121,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, tagRef, snapshot)),
onError: HandlePollError,
backoffCap: PollBackoffCap,
+ onBatch: (handle, items) => OnDataChangeBatch?.Invoke(this, new DataChangeBatchEventArgs(handle, items)),
// The engine owns no Meter (Core.Abstractions takes no metrics dependency), so this
// closure IS the production consumer of its overrun signal.
onOverrun: _ => OtOpcUaTelemetry.PollOverruns.Add(1,
@@ -972,9 +979,15 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
: $"TwinCAT device {unreachable.Options.HostAddress} unreachable ({unreachable.ConsecutiveProbeFailures} consecutive failed probes)");
}
- /// Raises one data change for a native subscription.
- private void RaiseDataChange(ISubscriptionHandle handle, string reference, DataValueSnapshot snapshot) =>
+ ///
+ /// Raises one data change for a native subscription on BOTH events: the per-tag one (legacy consumers)
+ /// and a one-item batch (a fresh list per raise — the consumer may retain it).
+ ///
+ private void RaiseDataChange(ISubscriptionHandle handle, string reference, DataValueSnapshot snapshot)
+ {
OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, reference, snapshot));
+ OnDataChangeBatch?.Invoke(this, new DataChangeBatchEventArgs(handle, [new DataChangeItem(reference, snapshot)]));
+ }
///
/// Registers one native notification and records its replayable intent on the device — both
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATBatchSubscribeTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATBatchSubscribeTests.cs
new file mode 100644
index 000000000..29148186c
--- /dev/null
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATBatchSubscribeTests.cs
@@ -0,0 +1,89 @@
+using System.Collections.Concurrent;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
+using ZB.MOM.WW.OtOpcUa.Driver.TwinCAT;
+
+namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests;
+
+///
+/// #739 / R02:P1 — TwinCAT is an . DriverInstanceActor subscribes ONLY the
+/// batch event of a batch-capable driver, so every data change — poll cycle AND native push, including the
+/// Bad snapshots the native path publishes itself — must reach OnDataChangeBatch; the per-tag event
+/// keeps firing for legacy consumers (the CLI).
+///
+[Trait("Category", "Unit")]
+public sealed class TwinCATBatchSubscribeTests
+{
+ private const string Host = "ads://5.23.91.23.1.1:851";
+
+ private static TwinCATDriver NewDriver(FakeTwinCATClientFactory factory, bool native) =>
+ new(new TwinCATDriverOptions
+ {
+ Devices = [new TwinCATDeviceOptions(Host)],
+ RawTags = TwinCATRawTags.Entries(
+ [
+ new TwinCATTagDefinition("A", Host, "MAIN.A", TwinCATDataType.DInt),
+ new TwinCATTagDefinition("B", Host, "MAIN.B", TwinCATDataType.DInt),
+ ]),
+ Probe = new TwinCATProbeOptions { Enabled = false },
+ UseNativeNotifications = native,
+ }, "drv-1", factory);
+
+ /// The driver advertises the batch capability.
+ [Fact]
+ public void Driver_is_batch_subscribable() =>
+ NewDriver(new FakeTwinCATClientFactory(), native: false).ShouldBeAssignableTo();
+
+ /// A poll cycle that changes two tags raises ONE batch carrying both, and the per-tag event twice.
+ [Fact]
+ public async Task A_poll_cycle_raises_one_batch_with_every_changed_tag()
+ {
+ var factory = new FakeTwinCATClientFactory
+ {
+ Customise = () => new FakeTwinCATClient { Values = { ["MAIN.A"] = 1, ["MAIN.B"] = 2 } },
+ };
+ var drv = NewDriver(factory, native: false);
+ await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
+ var batches = new ConcurrentQueue();
+ var single = new ConcurrentQueue();
+ drv.OnDataChangeBatch += (_, e) => batches.Enqueue(e);
+ drv.OnDataChange += (_, e) => single.Enqueue(e);
+
+ var handle = await drv.SubscribeAsync(["A", "B"], TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken);
+ await WaitForAsync(() => !batches.IsEmpty, TimeSpan.FromSeconds(3));
+ await drv.UnsubscribeAsync(handle, TestContext.Current.CancellationToken);
+
+ var first = batches.First();
+ first.SubscriptionHandle.ShouldBe(handle);
+ first.Items.Select(i => i.FullReference).ShouldBe(["A", "B"], ignoreOrder: true);
+ single.Count(e => e.FullReference is "A" or "B").ShouldBeGreaterThanOrEqualTo(2);
+ }
+
+ /// A native push and the native path's own Bad snapshot both reach the batch event.
+ [Fact]
+ public async Task Native_pushes_and_native_bad_snapshots_reach_the_batch_event()
+ {
+ var fake = new FakeTwinCATClient();
+ var drv = NewDriver(new FakeTwinCATClientFactory { Customise = () => fake }, native: true);
+ await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
+ var batches = new ConcurrentQueue();
+ drv.OnDataChangeBatch += (_, e) => batches.Enqueue(e);
+
+ _ = await drv.SubscribeAsync(["A", "Ghost"], TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken);
+ fake.FireNotification("MAIN.A", 42);
+
+ var items = batches.SelectMany(b => b.Items).ToList();
+ items.Single(i => i.FullReference == "Ghost").Snapshot.StatusCode.ShouldBe(TwinCATStatusMapper.BadNodeIdUnknown);
+ var a = items.Single(i => i.FullReference == "A");
+ a.Snapshot.StatusCode.ShouldBe(TwinCATStatusMapper.Good);
+ a.Snapshot.Value.ShouldBe(42);
+ }
+
+ private static async Task WaitForAsync(Func condition, TimeSpan timeout)
+ {
+ var deadline = DateTime.UtcNow + timeout;
+ while (!condition() && DateTime.UtcNow < deadline)
+ await Task.Delay(20);
+ }
+}