read / write
- Data Types OpcUaVariant and OpcUaDataValue It is the foundation of all reading and writing.
- For frequent access to the same node, please use register_nodes Accelerate.
- For real-time change notifications Subscription Rather than a loop that reads.
read
def read(self,
node_id: str,
attribute: AttributeId = AttributeId.Value) -> OpcUaDataValue: ...
Read the specified Attribute from a single node.
| Parameters | Type | Default | Note |
|---|---|---|---|
| node_id | str | — | NodeId String (i=2258 / ns=2; s=...) |
| attribute | AttributeId | Value (13) | Properties to Read |
Returns: OpcUaDataValue (context manager, Highly Recommended with)
Exception: OpcUaException (BadNodeIdUnknown / BadNotReadable / BadCommunicationError / ...)
from darra_opcua import AttributeId # Module Name darra_opcua
# Read Value
with ua.read("ns=2;s=Temperature") as dv:
print(dv.value) # Pythonic Decoding (Automatic DataType )
print(dv.variant.as_double) # Strong-Type Extraction
# Read DisplayName
with ua.read("ns=2;s=Temperature", AttributeId.DisplayName) as dv:
print(dv.value)
read_many
def read_many(self,
node_ids: List[str],
attribute: AttributeId = AttributeId.Value
) -> List[Optional[OpcUaDataValue]]: ...
Read the same attribute from multiple nodes in a single RPC batch.
nodes = ["ns=2;s=T1", "ns=2;s=T2", "ns=2;s=T3"]
results = ua.read_many(nodes)
for nid, dv in zip(nodes, results):
if dv is None:
print(f"{nid}: <failed>")
continue
with dv:
print(f"{nid} = {dv.value}")
Returns a length of len(node_ids), with the failed slot being None. Each non-None element is OpcUaDataValue (holds native memory and must be disposed of).
Performance: RPC Retrieving the same attribute from N nodes in a single operation read saves N-1 network round trips compared to using a loop. If the entire batch RPC fails (return code is non-0), the operation is aborted OpcUaException.
write
def write(self,
node_id: str,
value: OpcUaVariant,
attribute: AttributeId = AttributeId.Value) -> StatusCode: ...
Order-writing node.
from darra_opcua import OpcUaVariant, StatusCode # Module Name darra_opcua
st = ua.write("ns=2;s=Setpoint", OpcUaVariant().set_double(42.5))
if st != StatusCode.Good:
print(f"Write failed: {st.name}")
Returns StatusCode (Good / BadNotWritable / BadTypeMismatch / BadUserAccessDenied / ...).
write; exceptions are thrown only when value is None ( ValueError missing parameter). In all other cases—including transport-level failures—the return code is always converted to StatusCode and returned; no exception is thrown OpcUaException. You must check the return value; do not assume it is Good.
write Internal code does not consume the input OpcUaVariant; the OpcUaVariant user is still responsible for disposing of user-constructed objects. Recommendation:
v = OpcUaVariant().set_int32(42)
try:
ua.write("ns=2;s=Setpoint", v)
finally:
v.close()
# or "with" (abbreviated)
with OpcUaVariant().set_int32(42) as v:
ua.write("ns=2;s=Setpoint", v)
OpcUaVariant Quick Reference for Structures
from darra_opcua import OpcUaVariant # Module Name darra_opcua
import datetime as dt
# Flow Setter (Chainable, each set_* returns self)
OpcUaVariant().set_boolean(True)
OpcUaVariant().set_sbyte(-1)
OpcUaVariant().set_byte(255)
OpcUaVariant().set_int16(42)
OpcUaVariant().set_uint16(42)
OpcUaVariant().set_int32(42)
OpcUaVariant().set_uint32(42)
OpcUaVariant().set_int64(42)
OpcUaVariant().set_float(3.14)
OpcUaVariant().set_double(3.14)
OpcUaVariant().set_string("hello")
OpcUaVariant().set_datetime(dt.datetime.now(dt.timezone.utc))
The C layer only exports wide setters such as SetInt16, SetInt32, and SetUInt32, so they are set_sbyte passed through the channel Int16 —set_uint16 specifically, the UInt32 channel (with the value range still narrowed according to the parameters).
For more information, see OpcUaVariant Data Types.
OpcUaDataValue Field Quick Reference
| Field | Type | Note |
|---|---|---|
| value | Any | Pythonic Decoding (Automatically DataType converts to bool/int/float/str based on the inputdatetime) |
| variant | OpcUaVariant | Original OpcUaVariant (Borrows a handle; no need to call dispose) |
| status | StatusCode | Good / Bad* / Uncertain* |
| is_good | bool | == (status == StatusCode.Good) |
| source_timestamp | Optional[datetime] | Data Source Timestamp (UTC) |
| server_timestamp | Optional[datetime] | Timestamp set by the server (UTC) |
with ua.read("ns=2;s=T1") as dv:
if not dv.is_good:
print(f"Bad value: {dv.status.name}")
return
print(f"{dv.value} @ {dv.source_timestamp.isoformat()}")
AttributeId Common Values
| Id | Name | Note |
|---|---|---|
| 1 | NodeId | Node ID |
| 2 | NodeClass | Node Categories |
| 3 | BrowseName | Browse Name |
| 4 | DisplayName | Display Name |
| 5 | Description | Description |
| 13 | Value | Variable Value (Default) |
| 14 | DataType | Data Types NodeId |
| 17 | AccessLevel | Access permission bits |
| 20 | Historizing | Is history being recorded? |
| 21 | Executable | Is the Method Executable? |
Best Practices
- Lot Priority: For monitoring 100+ tags
read_many; do not use a loopread - Must be disposed of:
OpcUaDataValueHolds native memory; failing to dispose of it will cause a memory leak. Usewith. writeCheck the return value: Don't assume it's necessarily good- Use subscriptions for real-time changes: Do not poll with
readat 1-second intervals; instead, usecreate_subscriptionDataChange Events (Server-Side Push)