Subscription Auto-Recovery (TransferSubscriptions / Recreate)
Overview
After a session reconnects, the server-side subscription may still be alive (within LifetimeCount × PublishingInterval) or may already have been cleaned up. The SDK uses a two-step approach after a successful reconnect:
- TransferSubscriptions (Part 4 §5.13.7) — Transferring the Old Session to SubscriptionId the New One
- Recreate — If the transfer fails, rebuild Sub + All using the locally cached subscription parameters. MI
Rebuild Only Restore NodeId / Attribute / SamplingInterval / MonitoringMode / QueueSize / DiscardOldest These items; DataChangeFilter / EventFilter / Triggering links No Follow the recovery process (see "Scope of Recovery" below for the reason).
Business Side Not required Manually trigger the rebuild; notifications are sent via the event channel throughout the process UI.
Corresponding section of the specification: Part 4 §5.13.7 (TransferSubscriptions) / §5.12 (CreateSubscription).
API
| Methods / Events | Category | Reading and Writing | Note |
|---|---|---|---|
| ua.TransferSubscriptions(subscriptionIds, sendInitialValues = true) | Methods | Write | Manually transfer the old sub to the current session, returning each subscription StatusCode; throw an exception if the top-level operation fails. OpcUaException |
| ua.Events.SubscriptionRestored | Event | Read | Recreation Successful (This message is displayed for both "Transfer" and "Recreate") |
| ua.Events.Any (Category = SubscriptionLost / SubscriptionRestored) | Event | Read | Subscription Lost / Restored Unified Channel Entries |
public IReadOnlyList<StatusCode> TransferSubscriptions(
IReadOnlyList<uint> subscriptionIds,
bool sendInitialValues = true);
Subscription lostNoua.Events.SubscriptionLost Regarding strongly typed events, subscription loss notifications are currently routed through a single channel. If you want to know about subscription loss, please attach the event ua.Events.Any and monitor it Category == OpcUaEventCategory.SubscriptionLost.
Code Example
using DarraOpcUa_Client;
using var ua = new DarraOpcUa("opc.tcp://localhost:4840");
ua.Connect();
// 1) Event registration (Subscription loss is handled through a unified channel; strongly typed—currently SubscriptionLost unavailable)
ua.Events.Any += (s, e) =>
{
if (e.Category == OpcUaEventCategory.SubscriptionLost)
Console.WriteLine($"订阅丢失: {e.Source}, 原因={e.StatusCode}, 消息={e.Message}"); // Source: in the form of "sub=3"
};
ua.Events.SubscriptionRestored += (s, e) =>
{
Console.WriteLine($"订阅已恢复: {e.Source}"); // Source: "sub=3→7, 3 have been rebuilt MI"
};
// 2) Create a subscription + MI
using var sub = ua.CreateSubscription(500);
uint mi = sub.Add("ns=2;s=Temp", AttributeId.Value, 200,
MonitoringMode.Reporting, 10, true,
new DataChangeFilter { DeadbandType = DeadbandType.Absolute, DeadbandValue = 0.5 });
sub.DataChanged += (s, e) =>
{
Console.WriteLine($"{e.ValueString} @ {e.SourceTimestamp}"); // The callback fields have been extracted.
};
// 3) Unplug the Ethernet cable for 30 seconds, then check the logs:
// Reconnecting → Reconnected → SubscriptionRestored
// DataChanged Automatically resume; sampling/mode/queue parameters will be restored, but will DataChangeFilter not be restored
// 4) Manual Transfer (The business knows that the server has temporarily reset but the subscription is still active)
// Note: sub.SubscriptionId These are just display values (see ./create); the server will likely not recognize them.
var oldIds = new uint[] { sub.SubscriptionId };
var rcs = ua.TransferSubscriptions(oldIds, sendInitialValues: true);
foreach (var rc in rcs) Console.WriteLine($"Transfer: {rc}");
Recovery Process
Session Reconnected
↓
For each local Subscription:
1. Call TransferSubscriptions(oldSubId)
├─ Good → SubscriptionRestored event ("Transfer 恢复"), done
└─ Other status codes (including when the server does not support transfer) → go to 2
2. Create a new Sub with the creation-time publishingInterval + cached lifetime/keepAlive/priority
3. Rebuild all MI in the original subscription parameter order (the server-side mi handle will change)
├─ Restore SamplingInterval / Mode / QueueSize / DiscardOldest
└─ Do not restore DataChangeFilter / EventFilter / Triggering
4. SubscriptionRestored event ("已重建 N 个 MI, 失败 M")
The event subscription side is a separate process: Re-attach the event based on the target node in the cache MI, Similarly, do not replay the filter criteria; If the target node is not cached, only send the event SubscriptionLost and abort.
Scope of Restoration
| Item | After reconstruction |
|---|---|
| NodeId / Attribute | Restore |
| SamplingIntervalMs / QueueSize / DiscardOldest | Restore |
| MonitoringMode | Restore |
| DataChangeFilter | Do not restore — Cached locally only; never sent to the server (see DataChangeFilter) |
| EventFilter (SelectClauses / WhereClause) | Do not restore — Events still use the default 5 fields (see EventFilter) |
| Triggering links | No restoration, no caching (See Triggering Links) |
| MonitoredItem handle | Will change — Old handle is no longer valid |
Cached Fields
Parameters that each instance MI will remember:
- NodeId / Attribute
- SamplingIntervalMs
- MonitoringMode (Disabled / Sampling / Reporting)
- QueueSize / DiscardOldest
- The object
DataChangeFilterthat was originally passed in — Stored locally only; not distributed during a rebuild
The event subscription side caches only the target node and the incoming filter object; the filter is not propagated either.
After rebuilding, the server's handle mi will change, Business-Side NodeId Reconciliation: Use sub.MonitoredNodeIds to look up the current handle, or use directly sub.RemoveByNodeId(nodeId). The handle value is valid only for the current subscription lifecycle; its stability across rebuilds is not guaranteed.
Best Practices
- Do not persist the handle —
sub.AddThe returned value will changemiafter "Recreate"; to reconcile, press NodeId (sub.MonitoredNodeIds/RemoveByNodeId) - Hang
SubscriptionRestoredEvent —e.SourceIf it contains "N rebuilt MI, M failed," it can be displayed directly - Do not manually trigger a rebuild — Subscriptions SDK are automatically restored after a session reconnection; duplicate triggers will simply be queued.
- The lifetime can only be changed
Modifyby modifying —CreateSubscriptionDoes not accept the "lifetime" parameterModify(publishingIntervalMs, lifetimeCount = 1200, maxKeepAliveCount = 50, ...).lifetimeCount × publishingIntervalIf it's too short, the sub is lost due to minor network fluctuations; if it's too long, server resources accumulate. - Just adjust the parameters
Modify—ModifyAfter a successful operation, save the new parameters SDK based on the "revised" value returned by the server; when rebuilding, use the new values.
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| ua.TransferSubscriptions | ua.transfer_subscriptions | transferSubscriptions | TransferSubscriptions | transfer_subscriptions | DarraUa_Session_TransferSubscriptions |
| ua.Events.Any (Category=SubscriptionLost) | ua.events.subscription_lost.append(cb) | events.onSubscriptionLost(...) | events.OnSubscriptionLost(...) | events.on_subscription_lost(...) | DarraUa_Subscription_SetStateCallback |
| ua.Events.SubscriptionRestored | ua.events.subscription_restored.append(cb) | events.onSubscriptionRestored(...) | events.OnSubscriptionRestored(...) | events.on_subscription_restored(...) | (None; C SDK Not automatically rebuilt; the business side must confirm after rebuilding.) |
Side CNoneDarraUa_RegisterSubLostHandler / DarraUa_RegisterSubRestoredHandler This type of event-driven registration function. Subscription status is uniformly handled via a DarraUa_Subscription_SetStateCallback single callback (DarraUa_SubscriptionState = UA_SUB_STATE_LIFETIME_EXPIRED / UA_SUB_STATE_RECREATING etc.); after a transfer failure, only the local subscription table is cleared C SDK, Do not rebuild automatically, so there is no "Restored" notification; the business side is responsible for verifying the results of the restoration. The session-layer state is DarraUa_Session_SetStateCallback.