日本語 English

How to Connect to a PLC via OPC UA with Python (No Security)

Synchronous communication

Let's try synchronous communication in python3 using python-opcua from the Free OPC-UA Library

Install opcua

In the command prompt


> pip install opcua
	

Python code

Reads the value of the variable 'uaInt' on the PLC at IP address 192.168.0.21

opcuaclient.py

from opcua import Client

if __name__ == "__main__":
    client = Client("opc.tcp://192.168.0.21:4840")
    try:
        client.connect()
        var = client.get_node("ns=4;s=uaInt")
        value = var.get_value()
        print(f'value={value}')

    finally:
        client.disconnect()

Specify the variable to read with client.get_node()
The ns=4; in var = client.get_node("ns=4;s=uaInt") was taken from this NodeID

UaExpert
OPC UA NodeID checked in UaExpert

Result

Running it in the command prompt gives


> python3 opcuaclient.py
Requested session timeout to be 3600000ms, got 60000ms instead
value=0
	

Asynchronous communication

Let's try asynchronous communication in python3 using opcua-asyncio from the Free OPC-UA Library
opcua-asyncio is supported on python 3.7 or later

Install asyncio

In the command prompt


> pip install asyncua
	

Python code

Reads the value of the variable 'uaIntAry' on the PLC at IP address 192.168.0.21

opcuaclient_async.py

import asyncio
from asyncua import Client

async def main():
  url = 'opc.tcp://192.168.0.21:4840'
  async with Client(url=url) as client:
      var = client.get_node("ns=4;s=uaIntAry")
      value = await var.read_value()
      print(f'value={value}')

if __name__ == '__main__':
  asyncio.run(main())
	

Specify the variable to read with client.get_node()
The ns=4; in var = client.get_node("ns=4;s=uaIntAry") is taken from the NodeID as in the synchronous case

Result

Running it in the command prompt gives


> python3 opcuaclient_async.py
Requested session timeout to be 3600000ms, got 60000ms instead
value=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
	

FAQ

How do I connect to a PLC with python-opcua?

Install the library with pip install opcua, create a Client object, connect() and then read values by specifying the NodeId.

Where can I find the NodeId?

Install the library with pip install opcua, create a Client object, connect() and then read values by specifying the NodeId.

What is asyncua?

An OPC UA library that supports Python's asyncio, allowing data acquisition with asynchronous communication.

What is the standard OPC UA port number?

Port 4840 is normally used.

Related pages

GitHub

To learn more about the Free OPC-UA Library, see GitHub
Free OPC-UA Library

Comments