PLCcom OPC UA PubSub SDK class library documentation
First steps PLCcom OPC UA PubSub SDK for Java
The PLCcom OPC UA PubSub SDK for Java is an add-on for the PLCcom OPC UA SDK for Java. It adds OPC UA publisher/subscriber communication to applications that already use, or want to use, the PLCcom OPC UA SDK. The add-on is released in the same version as the main SDK and is intended to be used together with the matching PLCcom OPC UA SDK version.
The main SDK provides the classic OPC UA client and server world. The PubSub add-on extends this with message based communication: a publisher sends process values through UDP or MQTT, and one or more subscribers receive and process these values. This is useful for telemetry, machine-to-machine communication, broadcast or multicast scenarios and broker based MQTT integration.
Where to get the add-on
The PubSub SDK is distributed as an add-on to the PLCcom OPC UA SDK. It requires a valid PLCcom OPC UA SDK installation and license information that includes PubSub usage rights. Trial and commercial information are available on the PLCcom OPC UA SDK product pages.
| Resource | Purpose |
|---|---|
| PLCcom OPC UA SDK overview | Product information for the PLCcom OPC UA SDK family. |
| Trial download | Download entry point for evaluation and trial use. |
| Purchase information | Commercial license and ordering information. |
| Public Java examples on GitHub | Complete Java examples for the PLCcom OPC UA SDK and the PubSub add-on. |
Prerequisites
Before you add PubSub to an application, make sure that the basic SDK environment is available. The PubSub SDK is not a standalone replacement for the main PLCcom OPC UA SDK. It is an add-on and uses the main SDK types, license handling and certificate handling.
- PLCcom OPC UA SDK for Java in the same version as the PubSub add-on
- License information that includes the PubSub add-on usage rights
- Java runtime 1.8 or higher for applications
- A Java development environment that can compile Java 1.8 compatible code
- Maven, when the SDK is referenced through Maven coordinates
- An MQTT broker, when MQTT or secure MQTT transport is used
- A PKI and trusted certificates, when TLS protected MQTT communication is used
The PLCcom SDK artifacts must be available to Maven, for example in the local Maven repository or in a company Maven repository. If the artifacts are not available from a configured repository, install or deploy the SDK and PubSub artifacts according to your delivery package or build process.
Using the add-on with Maven
The PubSub add-on is referenced like any other Maven library. The version should always match the version of the main PLCcom OPC UA SDK used by the application.
<dependencies>
<dependency>
<groupId>com.indi-an.plccom</groupId>
<artifactId>plccom-opc-ua-pubsub</artifactId>
<version>10.x.x</version>
</dependency>
</dependencies>
Replace 10.x.x with the version delivered with your PLCcom SDK
package. The PubSub add-on and the main PLCcom OPC UA SDK are released with the
same version. The main SDK dependency is referenced by the PubSub artifact and
is normally resolved transitively by Maven.
Important note
With the PLCcom OPC UA PubSub SDK you or the user will be able to exchange process data between applications, machines or similar systems at your own discretion. For this purpose the user has to have the required knowledge and must understand the effects of the created application.
Before the resulting work can be applied to the plant, machine or similar, the creator of a project must test all functions and check function and interactions with the system, machine or similar. These tests are to be repeated after every software change and after every change to the system, machine or similar or the periphery (network, broker, certificates, server, etc.). If malfunctions occur or are detected, the PLCcom OPC UA PubSub SDK must not be operated at the plant, machine or similar.
What is OPC UA PubSub?
OPC UA PubSub extends the well-known OPC UA client/server communication model. In the classic model, a client connects to a server, opens a session and reads, writes or monitors nodes. In the PubSub model, a publisher sends DataSet messages and one or more subscribers receive them.
The data is described by DataSets and fields. A transport such as UDP or MQTT delivers the messages. Depending on the selected encoding and transport, PubSub can be used for local UDP communication, multicast distribution, broker based MQTT communication or TLS protected MQTT scenarios.
What PLCcom OPC UA PubSub SDK has to offer
The add-on provides a high-level Java API for creating PubSub publishers and subscribers. The configuration stays explicit and readable: choose the transport, define the published fields, enable discovery if needed and then start the publisher or subscriber.
Communication and encoding
- UADP NetworkMessage support
- JSON NetworkMessage support
- UDP unicast communication
- UDP multicast communication
- UDP broadcast communication
- MQTT transport for UADP and JSON messages
- MQTT over WebSocket with the ws and wss endpoint schemes
- Secure MQTT with TLS broker certificate validation
Application API
- High-level UaPublisher and UaSubscriber classes
- Fluent configuration builders for Publisher and Subscriber
- Named field access for received DataSet messages
- Publisher and Subscriber diagnostic events
- Simple Start(), Stop() and close() lifecycle
- WriteValue and WriteValues methods for updating published field values
- WriteDataValue and WriteDataValues methods for publishing values together with their StatusCode and timestamps
- Received per-field StatusCode and timestamps through getDataValueFields()
PubSub features
- PubSub discovery for DataSetMetaData exchange
- Proactive DataSetMetaData announcement over UDP and over MQTT, secured or in the clear
- Static DataSetReader field configuration when discovery is not desired
- KeyFrame and DeltaFrame handling for UADP DataSet messages
- Optional DataValue field encoding for per-field StatusCode and timestamps
- PKI based certificate handling in the familiar PLCcom SDK style
- Optional client certificate support for mutual TLS scenarios
- OPC UA PubSub UADP message security for applications that provide the required key material, for UADP over UDP and for UADP over MQTT
Basic PubSub terms
| Term | Meaning in application code |
|---|---|
| Publisher | Sends DataSet messages through the configured transport. |
| Subscriber | Receives DataSet messages and raises data events. |
| PublishedDataSet | A named group of values that belongs together. |
| Field | One logical value inside a DataSet, for example "Temperature". |
| DataSetReader | Describes what a subscriber expects to receive. |
| Discovery | Optional metadata exchange so a subscriber can learn the field layout. |
Create and start a publisher
A publisher configuration describes what is sent and how it is transported. The following example publishes three machine values by using UADP over UDP. Each field has a logical PubSub name and a NodeId that identifies the value in the publisher data store.
UaPublisherConfiguration publisherConfiguration =
UaPublisherConfiguration.Build("MachineTelemetryPublisher",
"opcua:MachineTelemetry")
.WithTransport(PubSubTransportMode.DirectUnicast,
"opc.udp://localhost:4840")
.WithDiscovery("opc.udp://localhost:4841")
.WithPublishingInterval(1000)
.AddDataSet("MachineTelemetry", ds -> ds
.AddField("Temperature", new NodeId(1001, 2))
.AddField("Pressure", new NodeId(1002, 2))
.AddField("Speed", new NodeId(1003, 2))
.WithKeyFrameCount(10)
.WithInterval(1000))
.build();
After the configuration has been created, construct the publisher with your PLCcom license information and call Start(). The WriteValue method updates the current value of a field. The next scheduled publish cycle sends the changed values according to the DataSet configuration.
try (UaPublisher publisher =
new UaPublisher(userName, serialNumber, publisherConfiguration)) {
publisher.addErrorListener(event -> {
System.out.println(event.getMessage());
if (event.getException() != null) {
event.getException().printStackTrace();
}
});
publisher.Start();
publisher.WriteValue("MachineTelemetry", "Temperature", 42.5);
publisher.WriteValue("MachineTelemetry", "Pressure", 6.2);
publisher.WriteValue("MachineTelemetry", "Speed", 1450.0);
// Keep the application alive while publishing is required.
// Call publisher.Stop() when publishing should be stopped explicitly.
}
Publishing values with quality and timestamp
WriteValue sends the plain value. When a field should also carry its own StatusCode and source timestamp, the PublishedDataSet switches to DataValue field encoding. The DataSetFieldContentMask follows OPC UA Part 14: StatusCode is bit 0x01 and SourceTimestamp is bit 0x02. Only the attributes selected by the mask are written to the wire. The default mask 0 keeps the classic Variant encoding, so existing configurations produce exactly the same messages as before.
UaPublisherConfiguration publisherConfiguration =
UaPublisherConfiguration.Build("MachineTelemetryPublisher",
"opcua:MachineTelemetry")
.WithTransport(PubSubTransportMode.DirectUnicast,
"opc.udp://localhost:4840")
.AddDataSet("MachineTelemetry", ds -> ds
.AddField("Temperature", new NodeId(1001, 2))
.WithDataSetFieldContentMask(
DataSetFieldContentMask.STATUS_CODE
| DataSetFieldContentMask.SOURCE_TIMESTAMP))
.build();
WriteDataValue then stores the supplied DataValue unchanged, so its StatusCode and SourceTimestamp are the ones the subscriber sees. WriteDataValues writes several fields in a single call. Fields written with the plain WriteValue are still transported; they simply get a Good StatusCode and the write time as source timestamp.
publisher.WriteDataValue("MachineTelemetry", "Temperature",
new DataValue(new Variant(42.5), StatusCode.GOOD,
DateTime.currentTime(), null));
Create and start a subscriber
A subscriber configuration describes what is received and which transport is used. When discovery is configured and no static fields are defined for the DataSetReader, the subscriber can request the DataSetMetaData from the publisher and use the discovered field names.
UaSubscriberConfiguration subscriberConfiguration =
UaSubscriberConfiguration.Build("MachineTelemetrySubscriber")
.WithTransport(PubSubTransportMode.DirectUnicast,
"opc.udp://localhost:4840")
.WithDiscovery("opc.udp://localhost:4841")
.AddDataSetReader("opcua:MachineTelemetry",
"MachineTelemetry")
.build();
If discovery is not used, or if the field layout is intentionally fixed in the application, the fields can be listed directly in the DataSetReader configuration.
UaSubscriberConfiguration subscriberConfiguration =
UaSubscriberConfiguration.Build("MachineTelemetrySubscriber")
.WithTransport(PubSubTransportMode.DirectUnicast,
"opc.udp://localhost:4840")
.AddDataSetReader("opcua:MachineTelemetry",
"MachineTelemetry", ds -> ds
.AddField("Temperature")
.AddField("Pressure")
.AddField("Speed"))
.build();
The subscriber raises a DataReceived event when a DataSet message arrives. For UADP DeltaFrames the event can contain only the fields that changed. For KeyFrames and JSON messages the complete payload is available.
try (UaSubscriber subscriber =
new UaSubscriber(userName, serialNumber, subscriberConfiguration)) {
subscriber.addErrorListener(event -> {
System.out.println(event.getMessage());
if (event.getException() != null) {
event.getException().printStackTrace();
}
});
subscriber.addDataReceivedListener(event -> {
System.out.println("DataSet: " + event.getDataSetName());
System.out.println("Fields : " + event.getFields());
});
subscriber.Start();
// Keep the application alive while receiving is required.
// Call subscriber.Stop() when receiving should be stopped explicitly.
}
Reading quality and timestamp
When the publisher uses DataValue field encoding, the same event also carries the per-field StatusCode and timestamps. getFields() keeps returning the plain values, so existing application code is not affected. getDataValueFields() adds the DataValue information and stays empty for the classic Variant encoding.
subscriber.addDataReceivedListener(event -> {
for (Map.Entry<String, DataValue> entry : event.getDataValueFields().entrySet()) {
DataValue dataValue = entry.getValue();
System.out.println(entry.getKey()
+ " = " + dataValue.getValue()
+ ", status " + dataValue.getStatusCode()
+ ", source timestamp " + dataValue.getSourceTimestamp());
}
});
For the JSON transport the DataSetReader must know the mask, because a JSON DataValue object and a JSON Variant object cannot be told apart from the payload alone. Configure the same value the publisher uses, with WithDataSetFieldContentMask(...) on the DataSetReader. For UADP the mask is optional on the subscriber side, because the UADP DataSetMessage header already announces DataValue field encoding.
Announcing DataSetMetaData
A subscriber that knows the DataSetMetaData can bind its values by field NAME instead of by position on the wire. Without metadata, the position is the only thing that identifies a value, so inserting a field on the publisher side silently shifts every field behind it. Pull based discovery solves this with a request and a response. In addition, a publisher can announce its DataSetMetaData proactively at a fixed interval.
UaPublisherConfiguration publisherConfiguration =
UaPublisherConfiguration.Build("MachineTelemetryPublisher",
"opcua:MachineTelemetry")
.WithTransport(PubSubTransportMode.DirectMulticast,
"opc.udp://239.0.0.1:4840")
.AnnounceMetaData(5000)
.AddDataSet("MachineTelemetry", ds -> ds
.AddField("Temperature", new NodeId(1001, 2))
.AddField("Pressure", new NodeId(1002, 2)))
.build();
- UDP: the announcement is sent to the same destination as the data messages. It therefore also reaches broadcast and multicast groups, where a request and response discovery endpoint cannot be bound. It works on unsecured and on secured WriterGroups.
- MQTT: the announcement is published on its own topic branch,
<prefix>/metadata/<DataSetName>, with the MQTT RETAIN flag. A subscriber that starts later therefore receives the current field layout from the broker immediately, instead of waiting for the next announcement interval.
On a secured WriterGroup the announcement is protected with the same SecurityGroup keys as the data messages by default. Use AnnounceMetaDataSecurity(UaMetaDataAnnounceSecurity.UNSECURED) to send it in the clear on purpose, for example so that simple third-party receivers without the keys can still read the field layout. The data messages stay secured either way.
The subscriber side needs no additional configuration. An announced DataSetMetaData is validated and applied exactly like a discovery response, and the subscriber raises the same discovery events. In such an event getDataSetName() reports the DataSet name announced by the remote publisher, while getReaderDataSetName() reports the name of the local DataSetReader. The two differ when a reader is bound to a remote DataSet with a different name.
Only interoperability mappings that do not use the default metadata topic need an override: MqttMetaDataTopic(...) on the publisher and mqttMetaDataTopicFilter(...) on the subscriber.
Using MQTT and secure MQTT
For broker based communication, use an MQTT transport mode and an MQTT broker endpoint. The same Publisher and Subscriber pattern is used. Only the transport endpoint changes, for example:
UaPublisherConfiguration publisherConfiguration =
UaPublisherConfiguration.Build("EnergyPublisher", "opcua:Energy")
.WithTransport(PubSubTransportMode.BrokerMqttJson,
"mqtt://localhost:1883")
.AddDataSet("Energy", ds -> ds
.AddField("Voltage", new NodeId(2001, 2))
.AddField("Current", new NodeId(2002, 2))
.AddField("Power", new NodeId(2003, 2)))
.build();
Four broker endpoint schemes are accepted. Besides plain and TLS protected MQTT, MQTT can also run over WebSockets, which is often the only way through a company proxy or a firewall that allows web traffic only.
| Endpoint scheme | Meaning | Default port |
|---|---|---|
mqtt:// |
MQTT over TCP | 1883 |
mqtts:// |
MQTT over TLS | 8883 |
ws:// |
MQTT over a plain, unencrypted WebSocket | 80 |
wss:// |
MQTT over a TLS protected WebSocket | 443 |
The endpoint scheme is checked while the configuration is built. An unsupported or malformed broker URL is therefore reported at configuration time and not only when the publisher or subscriber is started.
For TLS protected broker connections use an mqtts or wss endpoint. WithMqttTls builds the TLS configuration from the SDK PKI directory in a single call; the second overload additionally passes an own client certificate for mutual TLS. Both methods declare GeneralSecurityException and IOException, so the calling method has to handle or declare them.
UaPublisherConfiguration publisherConfiguration =
UaPublisherConfiguration.Build("EnergyPublisher", "opcua:Energy")
.WithTransport(PubSubTransportMode.BrokerMqttJson,
"mqtts://broker.example.com:8883")
.WithMqttTls("./pki")
.AddDataSet("Energy", ds -> ds
.AddField("Voltage", new NodeId(2001, 2)))
.build();
Broker certificates are validated by the configured certificate handling. A broker certificate that is issued by a CA in issuer/certs or trusted/certs, or that is itself contained in trusted/certs, is accepted right away as long as it is time-valid; in that case nothing is written to the rejected certificate store. If no matching CA is found and no application override accepts it, the certificate is placed in the rejected certificate store and the connection fails. The user can inspect it there and move it by hand to trusted/certs; from then on it is accepted as long as it is time-valid. An expired or not-yet-valid certificate is refused and written to the rejected certificate store even when its CA lies in issuer/certs or the certificate itself lies in trusted/certs.
TLS protects the connection to the broker. It does not protect the PubSub message itself once the broker has received it. For protection between publisher and subscriber, OPC UA Part 14 UADP message security signs and optionally encrypts the NetworkMessage. It can be used with the direct UDP UADP transport and with UADP over MQTT. It cannot be combined with JSON over MQTT, because a JSON NetworkMessage has no UADP SecurityHeader; that combination is rejected while the configuration is built.
Licensing
The PLCcom OPC UA PubSub SDK is a separately licensed add-on. The license information is passed when a UaPublisher or UaSubscriber instance is created.
UaPublisher publisher =
new UaPublisher("[Enter your UserName here]",
"[Enter your Serial here]",
publisherConfiguration);
System.out.println(publisher.getLicenceMessage());
Evaluation mode
If you pass two empty strings for user name and serial number, the add-on runs for 15 minutes with the full functional scope during a debug session — enough to bring up a connection and transfer values. That way you can try the add-on out before you register. For uninterrupted work, generate yourself a free trial license (14 days).
UaPublisher publisher = new UaPublisher("", "", publisherConfiguration);
When the evaluation period ends, operation stops: a running publisher or subscriber halts and reports it on the error listener. The same applies when a time-limited license expires. The library never terminates your application. The add-on runs its own license query and therefore its own evaluation period, independent of the one of the main SDK.
Free trial license:
https://www.indi-an.com/en/plccom/opc-ua-sdk/opcua-download/
Examples and further steps
The public Java example repository contains complete, runnable example projects for the PLCcom OPC UA SDK and the PubSub add-on. These examples show the typical application structure, configuration style, console output and certificate handling used by the SDK.
Public repository:
https://github.com/Indi-An/PLCcom-OpcUaSdk-examples-java
The PubSub add-on and the main PLCcom OPC UA SDK should always be used in the same version.