Subscription Resumes Automatically
Overview
After the session is reconnected, the server-side subscription may still be active or it may have been cleaned up. Perform Subscription::recreate
only the first step:
- TransferSubscriptions — Pass the old one to SubscriptionId the current session
- Manual Rebuild — If the transfer fails, SDK Do not rebuild automatically, Push only "Warn" events and retain them
mi_cache; Top level: Do it yourselfSession::create_subscription+ Pressmi_cache_snapshot()to replayadd_node*
On the Rust side TransferSubscriptions, it only recreate(&self) -> StatusCode proceeds. After the transfer fails,
itNo Instead of creating a new sub or re-adding it MI, send a " SubscriptionLost Warn" message and return
StatusCode::BAD, and have the upper layer handle it according to the following process.
API
| Methods / Events | Category | Reading and Writing | Note |
|---|---|---|---|
| s.transfer_subscriptions(sub_ids, send_initial_values) | Methods | Write | Transfer Subscription, returns Result<Vec<StatusCode>, OpcUaError> |
| sub.recreate() | Methods | Write | Transfer recovery entry, return StatusCode (does not return a Result) |
| sub.mi_cache_snapshot() | Methods | Read | Take a snapshot of MonitoredItemSpec for reconstruction by the upper layer |
| s.events.lock().unwrap().on_subscription_lost | Event | Read | Vec Field, .push(Box::new(cb)) Registration |
| s.events.lock().unwrap().on_subscription_restored | Event | Read | Vec Field, Registration .push(Box::new(cb)) |
events is SessionPublic Fields (pub events: Arc<Mutex<OpcUaEvents>>), is not a method;
There is no SDK such ua.events() calling convention at all.
Code Example
use darra_opcua::{Session, AttributeId, DataChangeFilter, DeadbandType};
let mut s = Session::new("opc.tcp://localhost:4840")?;
// `events` is a public field; it is on_xxx a `Vec`, and is registered using `push` (the closure is `Fn + Send + Sync`).
s.events.lock().unwrap().on_subscription_lost.push(Box::new(|e| {
eprintln!("订阅丢失: sub_id={} will_reconnect={}", e.subscription_id, e.will_reconnect);
}));
s.events.lock().unwrap().on_subscription_restored.push(Box::new(|e| {
println!("订阅已恢复: {}", e.source);
}));
s.connect()?;
// Create "sub +" MI; remains unchanged throughout
let sub = s.create_subscription(500.0)?;
let filter = DataChangeFilter {
deadband_type: DeadbandType::Absolute, deadband_value: 0.5,
..Default::default()
};
let mi = sub.add_with_filter(
"ns=2;s=Temp", AttributeId::Value, 200.0, filter,
|args| println!("{:?} @ {:?}", args.value_string, args.source_timestamp),
)?;
// Unplug the network cable for 30 seconds, then check the logs:
// reconnecting → reconnected → subscription_restored
// Data is automatically carried over, and the filter is retained.
// Manual transfer
let rcs = s.transfer_subscriptions(&[sub.subscription_id()], true)?;
// If a transfer fails, it is SDK not automatically rebuilt; the upper layer must handle it on its own mi_cache .
if !sub.recreate().is_good() {
let new_sub = s.create_subscription(500.0)?;
for spec in sub.mi_cache_snapshot() {
new_sub.add_node_with(&spec.node_id, spec.attribute, spec.sampling_interval_ms, |args| {
println!("{:?} @ {:?}", args.value_string, args.source_timestamp);
})?;
}
}
Recovery Process
Reconnect succeeded
↓
For each local Subscription:
1. sub.recreate() internally goes through TransferSubscriptions(old_sub_id)
├─ Success → push the SubscriptionRestored event, return StatusCode::GOOD, all MI still intact
└─ Failure → push SubscriptionLost (Warn), return StatusCode::BAD, and stop here
2. [SDK does not do this] The upper layer calls Session::create_subscription(original publishing_interval_ms) to get a new sub
3. [SDK does not do this] Iterate the old sub.mi_cache_snapshot(), replay add_node_with one by one per spec
- spec.node_id / spec.attribute / spec.sampling_interval_ms
- spec.queue_size / spec.discard_oldest / spec.mode need separate modify_item / set_mode calls
- DataChangeFilter is fetched back from filter_cache, replayed with add_with_filter
4. Push the SubscriptionRestored event (the upper layer raises it itself or notifies the business directly)
Cached Fields
Subscription Two internal caches (pub(crate) mi_cache_snapshot() read-only on the business side):
| Cache | Content |
|---|---|
mi_cache | HashMap<u32, MonitoredItemSpec> |
filter_cache | HashMap<u32, DataChangeFilter> — Stored only DataChangeFilter; no cache EventFilter |
MonitoredItemSpec Field:
pub struct MonitoredItemSpec {
pub client_handle: u32,
pub node_id: String,
pub attribute: AttributeId,
pub sampling_interval_ms: f64,
pub queue_size: u32,
pub discard_oldest: bool,
pub mode: MonitoringMode,
}
EventFilter Not in the Cache / Triggering Links Not in the cache, After recovery, playback will not resume automatically; the business side must
re-register.filter_cache It also only overrides DataChangeFilter.
Upon restorationThe server-side ID mi may change, On the client side, use the returned add_node* local handle (i.e., the
args.monitored_item_handle / in the callback spec.client_handle) for reconciliation; do not persist the server ID.
Best Practices
- Reconcile using local handles; do not persist the server ID mi.
- Monitor
on_subscription_restored, and perform a manual rebuild within it - Do not call directly
on_subscription_lostwithinrecreate()(since the session may not have finished reconnecting yet). - After changing key parameters, pause and then resume
- The business side is responsible for maintaining items that need to be rebuilt (EventFilter /Triggering Links); the SDK cache is not overwritten.
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| TransferSubscriptions | transfer_subscriptions | transferSubscriptions | TransferSubscriptions | transfer_subscriptions | DarraUa_Session_TransferSubscriptions |