Skip to main content

read / write

Prerequisite Reading

read​

def read(self,
node_id: str,
attribute: AttributeId = AttributeId.Value) -> OpcUaDataValue: ...

Read the specified Attribute from a single node.

ParametersTypeDefaultNote
node_idstr—NodeId String (i=2258 / ns=2; s=...)
attributeAttributeIdValue (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 / ...).

Business-level failures do not throw exceptions

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​

FieldTypeNote
valueAnyPythonic Decoding (Automatically DataType converts to bool/int/float/str based on the inputdatetime)
variantOpcUaVariantOriginal OpcUaVariant (Borrows a handle; no need to call dispose)
statusStatusCodeGood / Bad* / Uncertain*
is_goodbool== (status == StatusCode.Good)
source_timestampOptional[datetime]Data Source Timestamp (UTC)
server_timestampOptional[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​

IdNameNote
1NodeIdNode ID
2NodeClassNode Categories
3BrowseNameBrowse Name
4DisplayNameDisplay Name
5DescriptionDescription
13ValueVariable Value (Default)
14DataTypeData Types NodeId
17AccessLevelAccess permission bits
20HistorizingIs history being recorded?
21ExecutableIs the Method Executable?

Best Practices​

  • Lot Priority: For monitoring 100+ tags read_many; do not use a loop read
  • Must be disposed of: OpcUaDataValue Holds native memory; failing to dispose of it will cause a memory leak. Use with.
  • write Check the return value: Don't assume it's necessarily good
  • Use subscriptions for real-time changes: Do not poll with read at 1-second intervals; instead, use create_subscriptionDataChange Events (Server-Side Push)

Next Step​