OPC-UA 和 MQTT:协议指南和 Python 实现

物联网 (IoT) 正在改变行业,它使从简单传感器到复杂工业机器等各种设备之间实现无缝通信。推动物联网系统发展的两个最突出的协议是OPC-UA (开放平台通信 – 统一架构)和MQTT (消息队列遥测传输)。

每种协议在促进数据交换方面都发挥着至关重要的作用,但它们的用例和优势却大不相同。本文探讨了这些协议的工作原理、它们的优势以及如何使用 Python 实现它们以创建强大的 IoT 解决方案。

为什么选择 OPC-UA 和 MQTT?

OPC-UA:专为工业自动化而打造

OPC-UA 是一种独立于平台、面向服务的协议,专门针对工业环境而设计。它提供:

  • 复杂的数据模型:与简单的遥测协议不同,OPC-UA 支持分层数据结构,使其适用于详细的机器对机器 (M2M) 通信。
  • 安全性:加密、身份验证和数据完整性等功能使 OPC-UA 成为工业自动化的安全选择。
  • 互操作性:通过遵循标准化信息模型,确保不同制造商的设备之间的无缝通信。
  • 丰富的功能:除了简单的数据交换之外,OPC-UA还支持订阅、事件监控和远程方法调用,使其成为SCADA系统、MES(制造执行系统)和IIoT(工业物联网)应用的理想选择。

MQTT:轻量级且实时

MQTT是一种轻量级的发布-订阅协议,专为资源受限的设备而设计。它提供:

  • 最小开销:MQTT 使用轻量级消息传递格式,使其对于低带宽网络来说非常高效。
  • 实时通信:发布-订阅模型允许客户端在发布更新后立即收到更新。
  • 可扩展性:以 MQTT 代理为中心,可在大规模物联网部署中支持数千台设备。
  • 灵活性:它是遥测和事件驱动应用的首选协议,例如智能家居、健康监测和联网汽车。

架构概述

OPC-UA

在OPC-UA系统中:

  • OPC-UA 服务器:设备或系统(例如传感器、PLC 或 SCADA 系统)托管数据并将其公开给客户端。
  • OPC-UA 客户端:应用程序或系统(例如,MES 或分析软件)连接到服务器以检索或订阅数据。
  • 安全通信:内置加密和访问控制确保安全的数据交换。
OPC-UA 和 MQTT:协议指南和 Python 实现
来源:Emqx.com

MQTT

在基于 MQTT 的架构中:

  • 发布者:设备(例如传感器、微控制器)将数据发布到 MQTT 代理。
  • 订阅者:应用程序或服务订阅感兴趣的主题以接收更新。
  • MQTT bBroker:充当中央枢纽,管理消息分发并确保可扩展性。
OPC-UA 和 MQTT:协议指南和 Python 实现

Python 实现

1. 设置 OPC-UA 服务器

以下是创建一个简单的 OPC-UA 服务器来显示温度传感器值的方法:

from opcua import Server
from datetime import datetime

# Create an OPC-UA Server
server = Server()

# Set server endpoint
server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")

# Add a namespace
namespace = server.register_namespace("IoT_Example")

# Create an object node
node = server.nodes.objects.add_object(namespace, "IoTDevice")

# Add a variable to the object
temperature = node.add_variable(namespace, "Temperature", 0)
temperature.set_writable()  # Allow variable to be writable

# Start the server
server.start()
print("OPC-UA Server is running at opc.tcp://0.0.0.0:4840/freeopcua/server/")

try:
    while True:
        # Update the temperature value
        temperature.set_value(35.5)  # Example value
        print(f"Temperature updated: {temperature.get_value()}")
except KeyboardInterrupt:
    print("Shutting down server...")
    server.stop()

2. 设置 OPC-UA 客户端

以下是从 OPC-UA 服务器检索温度数据的方法:

from opcua import Client

# Connect to the OPC-UA Server
client = Client("opc.tcp://127.0.0.1:4840/freeopcua/server/")  # Use the server's correct URL
client.connect()

print("Connected to the OPC-UA server.")

try:
    # Browse the root and objects node
    root = client.get_root_node()

    objects = root.get_child(["0:Objects"])

    # Get the IoTDevice node
    iot_device = client.get_node("ns=2;i=1")  # Replace with correct Node ID for IoTDevice


    # Fetch the Temperature variable
    temperature_node = client.get_node("ns=2;i=2")  # Use the correct Node ID found during browsing
    temperature_value = temperature_node.get_value()
    print(f"Current Temperature: {temperature_value}°C")

finally:
    # Disconnect from the server
    client.disconnect()
    print("Disconnected from the server.")

3. 设置 MQTT 发布者

使用 Python 将温度传感器数据发布到 MQTT 代理:

import paho.mqtt.client as mqtt

# MQTT Broker details
broker = "test.mosquitto.org"
port = 1883
topic = "iot/temperature"

# Create an MQTT client with explicit callbacks
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT broker!")
    else:
        print(f"Connection failed with code {rc}")

# Create and configure client
client = mqtt.Client()
client.on_connect = on_connect  # Assign connect callback

# Connect to the broker
client.connect(broker, port)

# Publish a message
client.loop_start()  # Start the network loop
client.publish(topic, "Temperature: 15.5°C")
print(f"Message published to topic '{topic}'")
client.loop_stop()  # Stop the loop

4. 设置 MQTT 订阅者

从 MQTT 代理接收并显示温度数据:

import paho.mqtt.client as mqtt

# MQTT Broker details
broker = "test.mosquitto.org"
port = 1883
topic = "iot/temperature"

# Define the callback functions explicitly
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT broker and subscribed to topic.")
        client.subscribe(topic)
    else:
        print(f"Connection failed with code {rc}")

def on_message(client, userdata, msg):
    print(f"Received message: {msg.payload.decode()} from topic: {msg.topic}")

# Create an MQTT client and explicitly assign callbacks
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

# Connect to the broker
client.connect(broker, port)

# Start the network loop to listen for messages
print("Listening for messages...")
client.loop_forever()

结论

OPC-UA 和 MQTT 在物联网系统中相辅相成。OPC-UA 为工业设备提供丰富、安全且结构化的通信,而 MQTT 则确保遥测和云集成的轻量级、可扩展数据分发。通过利用 Python,您可以无缝实现和集成这些协议以构建多功能物联网解决方案。这些 Python 示例为实际实现提供了一个起点。随着物联网生态系统变得越来越复杂,结合 OPC-UA 和 MQTT 将为效率和创新带来新的机会。

作者:Nikhil Makhija
译自:https://dzone.com/articles/opc-ua-mqtt-guide-protocols-python-implementations

本文来自作者投稿,版权归原作者所有。如需转载,请注明出处:https://www.nxrte.com/jishu/55873.html

(0)

相关推荐

发表回复

登录后才能评论