Session — OpcUaSession
OpcUaSession This is the main Client class; one instance corresponds to one OPC UA Session. All operations (read / write / browse / subscribe / call / history) originate from this object.
DarraOpcUaIt is a compatible aliasOpcUaSessionfor (DarraOpcUa = OpcUaSession), and the two are equivalent.
Subpage Redirect
- For structural and connection specifications, please refer to Constructor.
- For connecting/disconnecting, please refer to Connection Management.
- For single-item and batch read/write operations, please refer to read / write.
- For the unified channel for internal events, please refer to Events.
- For namespace lookup, please refer to Namespaces.
- For information on heartbeat and session keep-alive, please refer to KeepAlive.
Public Attributes
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Connections | endpoint_url | str | R | The endpoint URL specified at construction |
security_mode | MessageSecurityMode | R | Security Mode (NONE / Sign / SignAndEncrypt) | |
| Status | state | SessionState | R | Current session status (Disconnected / Connecting / Connected / Reconnecting / Closing / Failed) |
is_connected | bool | R | Whether the user is connected (= state == SessionState.Connected) | |
handle | int | R | C-layer native session handle (internal) | |
| Child Objects | nodes | NodeCollection | R | Lazy Load Node Accessor |
namespaces | NamespaceCollection | R | Namespace URI ↔ Index Conversion | |
| Events | events | OpcUaEvents | R | Collection of session-level events: state_changed / connected / disconnected / reconnecting / reconnected / keep_alive / communication_error / subscription_lost / node_removed / node_access_denied / node_type_changed / session_lost / server_state_changed / subscription_restored / any (each is a List[Callable], registered using .append) |
| Configuration | keep_alive_interval_ms | int | RW | KeepAlive heartbeat interval (default 10000 ms, <= 0 = disabled) |
auto_publish | bool | RW | Enables or disables the background publish thread (default value: False; the constructor parameter auto_publish_on_connect defaults to True and is automatically set to True in `connect()`) |
Public Methods
Connection Management
connect()— Establish a connection (Hello → SecureChannel → Session → Activate)disconnect()— Connection terminated by the user; the instance can reconnectdispose() / close()— Stop the heart + Close the native session + Release stack references (withautomatically called upon exitdispose)
Heartbeat and Release
publish(timeout_ms = 2000)— Manually trigger a Publish once; returnsStatusCode(usually does not need to be called)
Read / Write
read(node_id, attribute = AttributeId.Value)— Read a Single Node's Specified Attributeread_many(node_ids, attribute)— Batch Read (Single Attribute)write(node_id, value, attribute = AttributeId.Value)— Order Entry Node
Browse
browse(node_id, filter = NodeClass.Unspecified)— Single-page viewbrowse_many(node_ids, filter)— Batch Viewbrowse_with_paging(node_id, filter)— Includes ContinuationPoint page-turning supportbrowse_next(continuation_point, release = False)— Continue to the next pagetranslate_browse_paths(paths)— Batch parse the paths to NodeIdresolve(path, start_node_id = None)— Single-Path Parsingregister_nodes(node_ids)— Register for a Temporary High-Efficiency Plan NodeIdunregister_nodes(registered_node_ids)— Cancel Temporary NodeId
Subscribe
create_subscription(publishing_interval_ms = 500.0)— Create a data subscriptionsubscribe_events(node_id = None, existing_subscription = None)— Subscribe to Events (Alarms / Conditions)transfer_subscriptions(subscription_ids, send_initial_values = True)— Migrating Subscriptions Across Sessions
Method Call
call(object_node_id, method_node_id, inputs = None)— Call the node OPC UA Method
History
read_history(node_id, start_utc, end_utc, max_values = 0)— Read raw history (simplified entry point)read_history_modified(...)— Reading a history that includes revision recordsread_history_at_time(...)— Read the interpolated value at a specified time pointread_history_processed(...)— Aggregation (Avg / Min / Max / TimeAverage / ...)read_history_events(...)— Reading About Historical Eventsupdate_history(...)— Insert / Replace / Update Historydelete_history_range(...)— Delete history by time period
Control
cancel(request_handle)— Cancels pending requests in the session and returns the actual number of requests canceled by the server (int)
Safe variant (never throws an exception)
read_safe(node_id, attribute)→(StatusCode, Optional[OpcUaDataValue])write_safe(node_id, value, attribute)→StatusCodebrowse_safe(node_id, filter)→(StatusCode, List[Reference])call_safe(object_node_id, method_node_id, inputs=None)→(StatusCode, List[OpcUaVariant])read_history_safe(node_id, start_utc, end_utc, max_values = 0)→(StatusCode, List[OpcUaDataValue])
Advanced Search / Subintervals
browse_filtered(nid, node_class_filter, direction, reference_type_id, include_subtypes)— Directional + reference type filtering (currently reduced tobrowse+ client-side NodeClass filtering)read_range(node_id, range_, attribute)/write_range(node_id, range_, value, attribute)— Subarray read/write (NumericRange); Forward when the entire segment is involvedread/write, Throw an exception when the current segment is not the entire segmentNotImplementedError
Historical Streams
read_history_stream(node_id, start_utc, end_utc, batch_size = 1000)— Asynchronous generator, yields one item at a timeOpcUaDataValue(no cancellation parameter)
Server Information
read_server_status()— ReturnsServerStatus(includingbuild/state/ timestamp)read_server_state()— Returns theServerStateenumerationread_current_time()— ReturnsOptional[datetime]
Alarms and Conditions
acknowledge/confirm/add_comment/enable_condition/disable_condition/condition_refresh/condition_refresh2/one_shot_shelve/timed_shelve/unshelve— See Alarm and Confirmation
Complete Example
from darra_opcua import OpcUaSession, OpcUaVariant # Module Name darra_opcua
import time
with OpcUaSession("opc.tcp://localhost:4840") as ua:
ua.events.connected.append(
lambda e: print(f"Connected to {e.endpoint_url}"))
ua.events.disconnected.append(
lambda e: print(f"Disconnected: {e.message}"))
ua.connect()
# Read
with ua.read("ns=2;s=Temperature") as dv:
print(f"T = {dv.value} °C")
# Write
st = ua.write("ns=2;s=Setpoint", OpcUaVariant().set_double(42.0))
print(f"Write status = {st.name}")
# Subscribe
with ua.create_subscription(500) as sub:
sub.data_changed.append(
lambda e: print(f"{e.node_id} = {e.value_string} ({e.status.name})"))
sub.add_node("ns=2;s=Counter")
# Methods
outputs = ua.call(
"ns=2;s=Calc", "ns=2;s=Calc.Add",
[OpcUaVariant().set_int32(3), OpcUaVariant().set_int32(4)])
for v in outputs:
with v:
print(f"sum = {v.as_int32}")
time.sleep(60)