Subscription Resumes Automatically
Overview
After a session reconnects, the server-side subscription may still be alive or may already have been cleaned up. The SDK uses a two-step approach for data subscriptions (Subscription):
- transfer_subscriptions — Pass the old one to SubscriptionId the current session
- Full Reconstruction — If the transfer fails, rebuild Sub + a batch using the settings from when it was created MonitoredItem
The business side does not need to manually initiate the recovery, butWhat You Need to Know About What Can't Be Recovered, See “Scope of Restoration” below.
During reconstruction,Restore Only NodeId / AttributeId / SamplingInterval / MonitoringMode / QueueSize / DiscardOldest. BelowNo Restore:
- DataChangeFilter — The filter will not be reattached during reconstruction
- EventFilter —
EventSubscriptionNo reconstruction logic - Triggering Links — Not part of the recovery process
- Dedicated MI to each
callback— Not retained after reconstruction; only the container-level listsub.data_changedremains (it is not destroyed when the subscription is deleted) add_manyAll items added in bulk MI — After reconnecting, none of the messages come back. If it can recover on its own,sub.add_node(...)add them one by one.
API
| Methods / Events | Category | Reading and Writing | Note |
|---|---|---|---|
| ua.transfer_subscriptions(subscription_ids, send_initial_values=True) | Session Methods | Write | Manually Transfer a Subscription, Returns List[StatusCode] |
| ua.events.subscription_lost.append(cb) | Event | Read | Subscription Lost (See warning below) |
| ua.events.subscription_restored.append(cb) | Event | Read | Subscription Resumption, Parameters SubscriptionRestoredEventArgs |
ua.events.subscription_lost this callback list at this timeExistence, but the current versionWill not be triggered. It won't throw an error when attached, but it will never be called. When recovery fails, it follows the ua.events.any channel, category OpcUaEventCategory.SubscriptionLost.
Code Example
from darra_opcua import (
DarraOpcUa, AttributeId, MonitoringMode,
)
with DarraOpcUa("opc.tcp://localhost:4840") as ua:
ua.connect()
# Subscription Resumption — Strongly Typed Event, with the following parameters: SubscriptionRestoredEventArgs
def on_restored(args):
print(f"订阅已恢复: sub_id={args.subscription_id} "
f"重建了 {args.monitored_item_count} 个 MI, {args.detail}")
ua.events.subscription_restored.append(on_restored)
# Restoration failed; take the "any" path (category = SubscriptionLost)
def on_any(e):
print(f"[{e.category.name}] {e.message} ({e.status_code.name})")
ua.events.any.append(on_any)
# Create "sub +" MI; remains unchanged throughout
sub = ua.create_subscription(500)
mi = sub.add_node("ns=2;s=Temp", attribute=AttributeId.Value,
sampling_interval_ms=200,
mode=MonitoringMode.Reporting, queue_size=10,
discard_oldest=True)
def on_dc(args):
print(f"{args.value_string} @ {args.source_timestamp}")
sub.data_changed.append(on_dc) # Container-level callbacks remain valid after a rebuild
# Unplug the network cable for 30 seconds, then check the logs:
# reconnecting → reconnected → subscription_restored
# Data is automatically appended; however, the dedicated MI callbacks and filters are gone.
# Manual Transfer (Requires a server-side perspective SubscriptionId; see the note below)
rcs = ua.transfer_subscriptions([server_sub_id], send_initial_values=True)
Recovery Process
events.reconnected fires
↓
1. transfer_subscriptions([subscription id], send_initial_values=True)
├─ result[0] == Good → events.subscription_restored(sub_id, rebuilt count, "Transfer 恢复...") → done
└─ Other / exception thrown → go to 2
2. Recreate a subscription,
reusing the original publishing / lifetime / keepalive / max_notifications / priority settings
3. Re-add each MI per the creation-time settings: add_node(node_id, callback=None, attribute, sampling_interval_ms)
├─ mode != Reporting → restore with set_mode
└─ queue_size != 1 or discard_oldest == False → restore with modify_item
4. events.subscription_restored(new sub_id, restored count, "已重建 N 个 MI[, 失败 M]")
and return StatusCode.Good
Step 4Unconditional Returns StatusCode.Good, even if all MI reconstructions fail. The number of failures is only listed in the SubscriptionRestoredEventArgs.detail text (in the format 「3 reconstructed MI, 2 failed」); please parse monitored_item_count and to determine this yourself detail, Don't subscription_restored just assume everything is fine because you see it.。
Step 1 uses a local approximation of the subscription ID —— Not from a server-side perspective SubscriptionId. Therefore, a "Transfer" is highly unlikely to succeed; in practice, it will default to Step 2, a full rebuild. ua.transfer_subscriptions(...) When manually triggering this on the business side, please provide the server ID that you have recorded SubscriptionId.
Settings Restored by the Reconstruction Tool
When rebuilding, restore the monitoring items to the settings they had when they were created: node_id / attribute / mode / sampling_interval_ms / queue_size / discard_oldest.
filter Passed only when created; not restored upon recreation. After reconstruction, the MI handle will change (add_node a new handle is returned), Do not persist the handle mi, Use node_id to reconcile the accounts.
Event Subscriptions (EventSubscription) do not automatically recover
Event subscriptions do not automatically resume after a session reconnection; the business logic must re-subscribe manually ua.subscribe_events(...).
Best Practices
- For business reconciliation
node_id; do not persist the mi handle (it will change after reconstruction). - Monitor
ua.events.subscription_restoredand checkmonitored_item_count/detaildetermine whether the reconstruction was truly successful - When recovery fails, follow the diagnostic path
ua.events.any(OpcUaEventCategory.SubscriptionLost), notsubscription_lostthat strongly typed event. - For business logic that requires per-containerMI callbacks, switch to container-level
sub.data_changeddistribution—container-level callbacks are not affected by reconstruction and remain valid after reconstruction. - The business side must handle event subscriptions on its own; SDK it doesn't matter
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| TransferSubscriptions | transfer_subscriptions | transferSubscriptions | TransferSubscriptions | transfer_subscriptions | DarraUa_Session_TransferSubscriptions |