The OPC UA protocol is a widely used protocol in Industrial Applications. Lately, many devices vendors have started including the protocol suite an support in their devices due to its popularity. Many PLC’s today are OPC UA enabled and it takes just a few steps to configure a server on a device.
However, sometimes you need to build your own custom OPC UA Server, say on an embedded board or on a system that does not have the protocol suite already enabled. In this demonstration therefore, we are going to see how to create an OPC UA server in python.
Step 1: Set up your OPC UA Client
OPC UA protocol is a Server – Client communication protocol. The Server hosts the nodes or some times known as tag variables and the client can access and manipulate the nodes depending on the read-write permillages set for each node. So to test our OPC UA server, we will need to have an OPC UA Client Ready. You can use a simulation OPC UA client or opt for a client implemented in python. Instructions on how to set up the two options can be seen here below.
Step 1.1: Simulation OPC UA Client
Step1.2: OPC UA Client implemented in Python
Step 2: Implementing the OPC UA Server
In this demonstration, the OPC UA server is implemented as a single python script and follows the following steps
Import the required packages
from time import sleep
import random
from opcua import Server
Create the server object and set the server endpoint
# create server
server = Server()
# create server endpoint
url = "opc.tcp://0.0.0.0:4840/opcua/server"
server.set_endpoint(url)
Register the server namespace
# create namespace
name = "OPCUA_SERVER"
idx = server.register_namespace(name)
Get the Objects Node, add an object to the Node and add a variable to the object
# get server objects node
objects = server.get_objects_node()
# add objects {namespace, object name}
param = objects.add_object(idx, "Parameters")
# add and initialise a variable to a specific object
temp = param.add_variable(idx, "Temperature", 0)
set read write privileges
# set read write privileges for a variable
temp.set_writable()
Start your server
# start server
server.start()
Update your variable however and whenever you want
temp.set_value(new_value)
Full Code
You can get the full code from github: brightersidetech/opcua_server_python