opc ua python examples

Master OPC UA with Python: Top Examples for Seamless Integration

By Matthew Walker
AD

For industrial automation professionals and developers, integrating OPC UA with Python has never been more accessible. The open-source ecosystem provides robust libraries that handle the complex machinery of the OPC UA protocol, allowing engineers to focus on building solutions rather than wrestling with network intricacies. This exploration into OPC UA Python examples serves as a practical guide for anyone looking to interface with industrial equipment, collect telemetry, or build custom supervisory applications.

Understanding the OPC UA Python Landscape

The foundation of any integration project is selecting the right toolkit. The primary library for this purpose is `freeopcua`, a feature-complete implementation of the OPC UA standard designed specifically for Python developers. This library allows Python to act as both a client, pulling data from machinery, and a server, exposing custom data points to other applications. Its architecture supports the full spectrum of OPC UA features, from node browsing and method calls to complex subscription management, making it suitable for both simple data logging and sophisticated distributed control systems.

Installing the FreeOpcUa Library

Getting started with OPC UA Python examples is straightforward thanks to the Python Package Index (PyPI). The `freeopcua` package is installed cleanly using the Pip package manager, which ensures all necessary dependencies are resolved automatically. This simplicity in installation removes a common barrier to entry, allowing developers to move from a blank screen to functional code in a matter of minutes. Once installed, the library is ready to establish secure connections with any standard OPC UA server.

AD
an image of a page that has been edited with the text python oop object - oriented programming notes
an image of a page that has been edited with the text python oop object - oriented programming notes
Python if Example Even Odd - EasyCodeBook.com
Python if Example Even Odd - EasyCodeBook.com
Python Basics Cheat Sheet for Beginners | Learn Coding Step by Step
Python Basics Cheat Sheet for Beginners | Learn Coding Step by Step

Client-Side Data Acquisition Example

The most common use case for OPC UA Python examples is acting as a client to read data points from a server. This scenario is typical for monitoring temperature, pressure, or status indicators from a PLC or a historian. The following code snippet demonstrates how to establish a secure connection, browse the address space to find a specific node, and asynchronously read its current value. This pattern is the bedrock of data acquisition scripts used in manufacturing and process automation.

Code Example: Secure Data Reading

Python Code
from asyncua import Client

async def main():
    # Initialize client with endpoint URL
    client = Client("opc.tcp://localhost:4840/freeopcua/server/")
    
    async with client:
        # Establish connection securely
        await client.connect()
        
        # Browse to a specific node
        my_node = client.get_node("ns=2;i=2")
        
        # Read the current value
        result = await my_node.read_value()
        print(f"Current Value: {result}")

# Run the async function
import asyncio
asyncio.run(main())

Server-Side Data Exposure and Custom Logic

While reading data is essential, the true power of OPC UA Python examples lies in the ability to create a server. This allows a Python application to expose its own data points to the wider industrial network, effectively becoming a data source for SCADA systems or HMIs. The server functionality enables developers to simulate machinery for testing, aggregate data from multiple sources, or expose the results of complex Python algorithms to operators. By becoming a server, Python moves from being a passive observer to an active participant in the industrial ecosystem.

a diagram showing the different types of python's programming skills and their uses in web design
a diagram showing the different types of python's programming skills and their uses in web design
Dice in python
Dice in python
Python Operators Tutorial – Chapter 3 Notes
Python Operators Tutorial – Chapter 3 Notes

Code Example: Simulated Server with Subscription

Python Code
from asyncua import Server
import asyncio
import random

async def main():
    server = Server()
    await server.init()
    
    # Configure server endpoint
    server.set_endpoint("opc.tcp://0.0.0.0:4841/freeopcua/server/")
    
    # Setup namespace
    uri = "http://examples.freeopcua.github.io"
    idx = await server.register_namespace(uri)
    
    # Get root node and add a variable
    objects = server.get_objects_node()
    myvar = await objects.add_variable(idx, "MyVariable", 0.0)
    await myvar.set_writable()  # Allow clients to write to this node
    
    async with server:
        print("Server started, updating value")
        # Simulate data change
        while True:
            val = random.randrange(1, 100)
            await myvar.write_value(val)
            print(f"Value updated to: {val}")
            await asyncio.sleep(1)

asyncio.run(main())

Error Handling and Security Considerations

Production-grade OPC UA Python examples must address security and resilience, not just basic connectivity. The protocol supports robust security policies, including encryption and user authentication, which are critical for protecting sensitive industrial data. When writing code, developers should implement structured error handling to manage network interruptions gracefully. Wrapping connection logic in try-except blocks and monitoring the connection state ensures that applications can recover automatically from downtime, a necessity for 24/7 industrial operations.

Advanced Integration Patterns

Moving beyond basic read/write operations, OPC UA Python examples can leverage the protocol’s extensibility for complex industrial scenarios. This includes utilizing historical access to retrieve time-series data for analysis, calling methods on devices to trigger specific actions, or using event subscriptions to react to changes in machine status in real-time. These advanced patterns transform a simple script into a powerful supervisory control application capable of driving automation workflows and providing valuable insights into operational efficiency.

AD
python aesthetic
python aesthetic
🌍✨ PYTHON FOR WORKING WITH APIs: INTEGRATE WITH THE WEB ✨🌍
🌍✨ PYTHON FOR WORKING WITH APIs: INTEGRATE WITH THE WEB ✨🌍
10 Python Tricks Every Beginner Should Know
10 Python Tricks Every Beginner Should Know
What is OOPs concept in Python
What is OOPs concept in Python
Python program that creates a queue using the queue module and then converts it into a list.
Python program that creates a queue using the queue module and then converts it into a list.
Phyton
Phyton
Python While Loop Examples
Python While Loop Examples
a computer screen with some text on it and an image of a cat in the background
a computer screen with some text on it and an image of a cat in the background
an image of a computer screen with text and numbers on it, including the words
an image of a computer screen with text and numbers on it, including the words
OOP Concepts in Python (Simple Explanation for Beginners)
OOP Concepts in Python (Simple Explanation for Beginners)
ImpπŸ’― Python functions
ImpπŸ’― Python functions
100 Python Project for beginners, intermediate and advanced programmers
100 Python Project for beginners, intermediate and advanced programmers
How To Iterate Through A List In Python, Choosing The Right Python Ide, Python List Methods Examples, Python List Methods Infographic, How To Implement One-to-many In Python, How To Use List Methods In Python, Best Ide For Python Development, Python List, Python Project Ideas List
How To Iterate Through A List In Python, Choosing The Right Python Ide, Python List Methods Examples, Python List Methods Infographic, How To Implement One-to-many In Python, How To Use List Methods In Python, Best Ide For Python Development, Python List, Python Project Ideas List
Python Syntax Guide Cheat Sheet πŸ’Ύβœ¨
Python Syntax Guide Cheat Sheet πŸ’Ύβœ¨
Python list exercises guide
Python list exercises guide
an image of a computer screen with text and numbers on it, including the same language as
an image of a computer screen with text and numbers on it, including the same language as
Python Unit 2 Cheat Sheet 🐍 | If-Else, Loops, Break & Continue (AKTU)
Python Unit 2 Cheat Sheet 🐍 | If-Else, Loops, Break & Continue (AKTU)
Python + Art = 🌹 Try This Fun Code!
Python + Art = 🌹 Try This Fun Code!
Python list methods cheat sheet
Python list methods cheat sheet
the top 50 python project ideas
the top 50 python project ideas
AD