Python · recipe

Read a value from an OPC UA server in Python

Read the whole DataValue, not just the number. It carries a status code and two timestamps, and code that discards them cannot later explain its own data. Resolve the namespace index from its URI rather than hardcoding it.

Stackasyncua (FreeOpcUa/opcua-asyncio)
Version2.0.1

The code

import asyncio
from asyncua import Client

async def main():
    async with Client(url="opc.tcp://opcua.umati.app:4840") as client:
        # resolve the namespace by URI - never hardcode ns=4
        idx = await client.get_namespace_index("http://opcfoundation.org/UA/MachineTool/")
        node = client.get_node("i=2258")   # Server CurrentTime, always present
        dv = await node.read_data_value()
        print("value           :", dv.Value.Value)
        print("status          :", dv.StatusCode)
        print("source timestamp:", dv.SourceTimestamp)
        print("server timestamp:", dv.ServerTimestamp)
        print("MachineTool ns  :", idx)

asyncio.run(main())

What it prints

value           : 2026-09-08 03:44:59.321000
status          : StatusCode(Good)
source timestamp: 2026-09-08 03:44:59.321000
server timestamp: 2026-09-08 03:44:59.321000
MachineTool ns  : 4

Notes

  • `read_value()` returns the bare value; `read_data_value()` returns the full DataValue. Prefer the latter anywhere the data will be stored or averaged.
  • A status of UncertainLastUsableValue means you are reading a stale cached value. Averaging it silently corrupts an OEE figure, so branch on the status.
  • `get_namespace_index(uri)` is the habit that stops your client breaking after a PLC program download.
  • One-liner without code: `uaread -u opc.tcp://opcua.umati.app:4840 -n "i=2258" -t`.

What breaks first

A hardcoded namespace index stops resolving after a server upgrade or PLC download BadNodeIdUnknown
Read the namespace array at connect and map URI to index. Store the URI and identifier in configuration, never the raw index.

Last verified 7 September 2026 against OPC UA 1.05.07. OPC UA Connect is an educational resource and is not affiliated with the OPC Foundation.

Free download
OPC UA Troubleshooting & Integration Checklist
The field-tested checklist engineers use to diagnose certificates, ports and namespace problems fast, plus a Python (asyncua) client template.
Get the free checklist →
Free, no course, no login