KeepAlive Heartbeat
Session built-in KeepAlive heartbeat: periodically reads ServerStatus.CurrentTime (i=2258) as a probe,
which both prevents the session from timing out and detects connection issues as soon as possible.
- For Heartbeat Event Callbacks, see Events.
- For the automatic reconnection process, please see Connection Management.
API
pub fn keep_alive_interval_ms(&self) -> u32;
pub fn set_keep_alive_interval_ms(&mut self, ms: u32);
| Item | Value |
|---|---|
| Unit | milliseconds |
| Default | 10000 (10 seconds) (changed in ConnectionConfig::keepalive_interval_ms) |
| Minimum Recommendation | 1000 |
| 0 | Disable |
Changes take effect immediately:
s.set_keep_alive_interval_ms(5000); // Change it to 5 seconds
Start-Stop System
| Timing | Behavior |
|---|---|
| After connect() succeeds | Automatic Startup |
| disconnect() | Auto-Stop |
| set_keep_alive_interval_ms(...) | Restart |
| Reconnection Successful | Automatic Startup |
KeepAlive is implemented std::thread independently (with no dependency on Tokio). Internally, it uses a stop Arc<AtomicBool> flag
to terminate threads, and adds a + stop.store(true) at the Drop Session same time join().
Heartbeat Incident
Triggered every time a heartbeat is successful on_keep_alive:
s.events.lock().unwrap().on_keep_alive.push(Box::new(|e| {
println!("KeepAlive @ {:?} (server status={})",
e.server_time_utc, e.server_status);
}));
Heartbeat Failure (Failure to Read CurrentTime) Triggered on_communication_error:
s.events.lock().unwrap().on_communication_error.push(Box::new(|e| {
if e.category == "keepalive" {
eprintln!("Heartbeat lost: {} {}", e.status_code, e.message);
}
}));
KeepAliveEventArgs:
pub struct KeepAliveEventArgs {
pub server_time_utc: SystemTime,
pub server_status: StatusCode,
pub timestamp_utc: SystemTime,
}
Relationship with SessionTimeout
There are two values to distinguish when it comes to session timeouts: clientRequest( session_timeout_ms ConnectionConfig, default 60 000 ms (60 seconds)),
The session timeout actually in effect after negotiation with the server (the RevisedSessionTimeout returned by CreateSession) is decided by the server;
it varies by server, so the value returned by the server takes precedence.
The client's KeepAlive must be significantly shorter than the active session timeout; otherwise, the server will proactively clean up the session due to "prolonged inactivity,"
and the client won't realize this until BAD_SESSION_ID_INVALID it receives the response.
| Valid Session Timeout (After Server Negotiation) | KeepAlive Interval |
|---|---|
| 60 seconds (SDK default value for the request) | 10 seconds (SDK default) |
| 5 minutes | 5 seconds |
| 1 hour | 30 seconds |
Why use ServerStatus.CurrentTime
OPC UA There is no dedicated KeepAlive protocol message; the common practice is to send a lightweight Read request as a heartbeat.
ServerStatus.CurrentTime (i=2258) is a standard OPC Foundation node; any
Server that complies with the specification has one, and the Read request incurs minimal overhead.
Custom Heartbeat Logic
If you want to completely disable the SDK built-in heartbeat, start your own thread:
use std::time::Duration;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
s.set_keep_alive_interval_ms(0); // Disable SDK Built-in
let stop = Arc::new(AtomicBool::new(false));
let stop2 = stop.clone();
// Wrap a Session in an Arc for cross-thread sharing (Session implements Send + Sync)
let s_arc = Arc::new(s);
let s2 = s_arc.clone();
std::thread::spawn(move || {
while !stop2.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_secs(5));
if !s2.is_connected() { continue; }
let _ = s2.read("i=2258"); // My Own Heartbeat
}
});
// Log Out
stop.store(true, Ordering::SeqCst);
Impact on Performance
KeepAlive overhead per instance:
- 1 Read RPC (Network round-trip + server-side read + serialization)
- The time required for a single operation varies depending on the network and server (with significant differences between local area networks and remote connections); test it in your actual environment.
The default heartbeat interval is 10 seconds (ConnectionConfig::keepalive_interval_ms), with only 1 Read request sent per interval; CPU / Determine the bandwidth usage based on actual testing in your environment.