Skip to main content

OPC UA → MQTT Bridging

OPC UA suits high-quality local communication, while MQTT suits large-scale public-network subscriptions. Bridging the two is the standard IIoT solution. Example in C# + MQTTnet.

Sample Configuration

Dependency​

dotnet add package Darra.OpcUa
dotnet add package MQTTnet

Complete Code​

using DarraOpcUa_Client;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

class Program
{
static async Task Main()
{
const string opcuaEndpoint = "opc.tcp://192.168.1.100:4840"; // Replace with an on-site industrial PC PLC IP
const string mqttBroker = "mqtt.example.com";
const int mqttPort = 8883;
const string topicPrefix = "factory1/opcua";

var nodes = new[]
{
"ns=2;s=Boiler1.Temperature",
"ns=2;s=Boiler1.Pressure",
"ns=2;s=Line1.Counter",
};

// 1. MQTT Client Connection
var mqttFactory = new MqttFactory();
var mqtt = mqttFactory.CreateMqttClient();
var mqttOpts = new MqttClientOptionsBuilder()
.WithTcpServer(mqttBroker, mqttPort)
.WithCredentials("factory1", "secret")
.WithTls()
.WithCleanSession()
.Build();
await mqtt.ConnectAsync(mqttOpts);
Console.WriteLine($"[OK] MQTT connected {mqttBroker}:{mqttPort}");

// 2. OPC UA Client Connection
using var ua = new DarraOpcUa(opcuaEndpoint);
ua.Connect();
Console.WriteLine($"[OK] OPC UA connected {opcuaEndpoint}");

// 3. Subscribe + Forward MQTT (JSON payload)
using var sub = ua.CreateSubscription(1_000);
sub.DataChanged += async (s, e) =>
{
var topic = $"{topicPrefix}/{e.NodeId.Replace(";", "_").Replace("=", "_")}";
var payload = JsonSerializer.Serialize(new
{
nodeId = e.NodeId,
value = e.ValueString,
status = e.Status.ToString(),
ts = e.SourceTimestamp,
});

await mqtt.PublishAsync(new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(payload)
.WithRetainFlag()
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
.Build());

Console.WriteLine($" -> {topic}: {e.ValueString}");
};

sub.AddMany(nodes);
Console.WriteLine($"\nBridging {nodes.Length} tags. Ctrl+C 退出...");
await Task.Delay(Timeout.Infinite);
}
}

Code Highlights​

  • Topic: Do not concatenate directly —NodeId includes separators ; =; factory-level naming is recommended <plant>/<line>/<device>/<tag> so that subscribers can use wildcards
  • QoS 0 (may be lost) is used for high-frequency telemetry; QoS 1 (may be re-transmitted) is the default; QoS 2 (slow) is used only for billing and command transmission.
  • The "Retain Flag" causes the broker to retain the most recent message for each topic; the status metric (switch/mode) must be enabled, while high-frequency telemetry may be disabled.
  • Public network bandwidth is expensive, so for high-frequency tags, apply dead zone filtering before bridging (only push updates when changes exceed X%); otherwise, bandwidth usage will skyrocket.
  • Outbound transmission (MQTT → ua.Write) uses a separate topic namespace (e.g., factory1/cmd/#), which is kept separate from upstream data to prevent loops.
  • Modify the Protobuf payload when integrating with Sparkplug B

Important Notes​

  • Public Network Bandwidth Is Expensive — For High-Frequency Tags, Perform the Operation on the Client Side Before BridgingDead Zone Filtering (Only push if the change exceeds X%; otherwise, it will cause a bandwidth spike.)
  • Reverse (MQTT send command →ua.Write) to another topic namespace (factory1/cmd/#), separate from upstream data, to avoid loops.
  • When interfacing with the Sparkplug B specification, change the payload to Protobuf instead of JSON.