C# / .NET · recipe
Use OPC UA PubSub in C#
The .NET reference stack is one of the few that implements Part 14 properly. Configure a publisher with a PublishedDataSet, a WriterGroup and a DataSetWriter, and choose UADP or JSON deliberately, non-reversible JSON silently loses type information.
| Stack | OPCFoundation/UA-.NETStandard |
|---|---|
| Version | 1.5.378.156 stable, 2.0.0-preview.2 |
The code
using Opc.Ua.PubSub;
using Opc.Ua.PubSub.Configuration;
// PubSub is configured declaratively. This is the shape of it:
var config = new PubSubConfigurationDataType
{
Connections = new PubSubConnectionDataTypeCollection
{
new PubSubConnectionDataType
{
Name = "MqttConnection",
Enabled = true,
PublisherId = new Variant((ushort)1),
TransportProfileUri = Profiles.PubSubMqttJsonTransport,
Address = new ExtensionObject(new NetworkAddressUrlDataType
{
Url = "mqtt://localhost:1883",
}),
WriterGroups = new WriterGroupDataTypeCollection
{
new WriterGroupDataType
{
Name = "WriterGroup1",
Enabled = true,
PublishingInterval = 1000,
WriterGroupId = 1,
// DataSetWriters reference a PublishedDataSet by name
},
},
},
},
};
using UaPubSubApplication app = UaPubSubApplication.Create(config);
app.Start();
Console.WriteLine("publishing; inspect the broker with MQTT Explorer");
What it prints
# MQTT Explorer, topic opcua/writergroup1:
{"MessageId":"...","MessageType":"ua-data","PublisherId":"1",
"Messages":[{"DataSetWriterId":1,"Payload":{"CurrentTime":{"Value":"2026-09-08T03:45:00.102Z"}}}]}
Notes
- PubSub is configured, not coded. Getting the configuration object right is the whole job, and it maps one-to-one onto the Part 14 model: connection, writer group, dataset writer, published dataset.
- Choose the encoding deliberately. Non-reversible JSON is smaller and human-readable but cannot be round-tripped because it discards type information.
- In JSON encoding, Good is 0 and is omitted. A missing status field means Good, not missing data: downstream consumers must be written knowing that.
- A subscriber joining mid-stream sees nothing until the next key frame. Set the key frame count with that in mind.
- PubSub has no session, so keys come from a Security Key Service rather than a handshake. Plan for it before you need security.
What breaks first
Downstream consumers cannot reconstruct types from the published JSON
Switch the dataset message encoding to reversible JSON or UADP. Non-reversible JSON is lossy by design.
BadDataEncodingUnsupportedSwitch the dataset message encoding to reversible JSON or UADP. Non-reversible JSON is lossy by design.
Other recipes in this stack
Concepts on this page
Last verified 7 September 2026 against OPC UA 1.05.07. OPC UA Connect is an educational resource and is not affiliated with the OPC Foundation.