PLCcom MQTT Client Java class library documentation



PLCcom



First steps PLCcom MQTT Client for Java

The PLCcom MQTT Client module is the Java API for applications that connect to an MQTT broker. It can publish messages, subscribe to topics, receive messages, use request/response workflows and configure MQTT 3.1.1 or MQTT 5.0 features without exposing the application to MQTT packet internals.

Start here: most applications begin with PlccomMqttClientFactory.builder(). The builder creates a PlccomMqttClient, and the client then performs connect(), publish(...), subscribe(...), receive(...) and close(). The fluent builders keep the normal path short while still exposing MQTT 5 details when they are needed.

PLCcom MQTT Client overview with application code, client API and broker interaction.

How to read this API

The high-level client API is organized around tasks instead of MQTT packet classes. Application code describes what it wants to do - connect, publish, subscribe, request a response or close - and the client performs the required MQTT packet exchange internally. This keeps normal application code compact but still gives advanced users access to MQTT 5 properties, TLS/PKI settings, diagnostics and lifecycle callbacks.

Connection setup
Use PlccomMqttClientFactory.builder() for endpoint, Client Identifier, MQTT version, TLS, credentials, Last Will and reconnect behavior.
Message exchange
Use publish(...), subscribe(...), receive(...), request(...) and their builders for payloads, QoS, retained messages and MQTT 5 metadata.
Operation result
Every relevant operation returns a PLCcom result object with quality information and, when needed, an inner exception for detailed troubleshooting.

Main entry points

Entry pointUse it whenTypical next step
PlccomMqttClientFactory.builder()You create a new client from readable high-level settings.Configure endpoint, identity, TLS, Last Will and diagnostics, then call build().
PlccomMqttClientYou want the synchronous API for straightforward command-style application code.Call connect(), then publish, subscribe, receive or request.
PlccomMqttAsyncClientYour application should not block the caller thread while MQTT operations are running.Use the CompletableFuture based methods from client.async().
MqttClientPublishBuilderA publish needs QoS, retain flag, JSON payloads or MQTT 5 properties.Set the publish details and finish with send().
MqttClientSubscribeBuilderA subscription needs callbacks, shared subscriptions, retained-message options or Subscription Identifiers.Set the filter and options and finish with start().
MqttClientRequestBuilderYou use the MQTT 5 request/response pattern with Response Topic and Correlation Data.Send the request and inspect the correlated response result.

Maven dependency


<dependency>
    <groupId>com.indi-an.plccom</groupId>
    <artifactId>plccom-mqtt-client</artifactId>
    <version>2.x.x</version>
</dependency>

Replace 2.x.x with the concrete PLCcom MQTT v2 release version you use. You do not normally add plccom-mqtt-core yourself. Maven resolves it transitively because the Client uses Core internally.

Minimal client

This example connects to a local broker, publishes one retained value with MQTT 5.0 and closes the network connection cleanly. A clean close matters because it tells the broker that the client disconnected intentionally and that no Last Will message should be published for this session.

The two empty strings are the license fields, shown blank on purpose: they turn on evaluation mode, so this example runs for 15 minutes during a debug session with the full functional scope. Fill both in from your license for uninterrupted work.


import com.plccom.mqtt.client.MqttPublishResult;
import com.plccom.mqtt.client.PlccomMqttClient;
import com.plccom.mqtt.client.PlccomMqttClientFactory;

public class MinimalMqttClient {
    public static void main(String[] args) throws Exception {
        try (PlccomMqttClient client = PlccomMqttClientFactory.builder("", "")
                .server("localhost", 1883)
                .identifier("example-client")
                .mqtt5()
                .build()) {

            client.connect();

            MqttPublishResult result = client.publish("factory/line1/temperature", 21.7)
                    .qos1()
                    .retain()
                    .send();

            System.out.println("Published with QoS " + result.qos());
        }
    }
}

Evaluation mode

Pass two empty strings as the license fields and the library runs for 15 minutes during a debug session with full functionality – enough to open a connection and read values. This lets you try the library before you register. For uninterrupted work, generate a free trial license (14 days): https://www.indi-an.com/en/plccom/mqtt/mqtt-download/

When the evaluation period ends, operation stops: an open connection is disconnected and a running broker halts. The same applies when a time-limited license expires. The library never terminates your application.

License data does not belong in source code. Use configuration files, environment variables or a secret manager to load it at runtime.

Configuration flow

StepWhat to configureTypical API
EndpointHost, port, URI scheme, WebSocket path and protocol selection.server(...), endpoint(...), mqtt5()
IdentityClient Identifier and optional username/password.identifier(...), usernamePassword(...)
SessionClean Start/Clean Session, Session Expiry and reconnect behavior.cleanStart(...), sessionExpirySeconds(...)
Transport securityTLS context, trust handling, client certificate and PKI store.tls(...)
Runtime feedbackLifecycle callbacks and diagnostic listener.onConnected(...), onDiagnostic(...)

Important MQTT terms in plain words

TermWhat it means for application code
Topic NameThe address of a message, for example factory/line1/temperature. Publishers send to Topic Names.
Topic FilterThe subscription pattern used by receivers. It may contain + or # wildcards, for example factory/+/temperature.
QoS 0Fast fire-and-forget delivery. The sender does not wait for an MQTT acknowledgement.
QoS 1At-least-once delivery. The sender waits for acknowledgement; duplicates are possible after reconnects.
QoS 2Exactly-once MQTT handshake. It is useful when duplicates are more harmful than the extra protocol round trips.
Retained MessageThe broker remembers the latest retained value for a Topic Name and can send it immediately to a later subscriber.
Last WillA message configured during CONNECT. The broker publishes it only if the client connection disappears unexpectedly.

High-level features to notice

  • publish(...) overloads for strings, byte arrays, numbers, booleans, lists and JSON payloads.
  • subscribe(...) builders with callbacks, subscription handles, shared subscriptions and MQTT 5 options.
  • request(...) and requestJson(...) for MQTT 5 request/response workflows.
  • async() for CompletableFuture based usage when blocking calls should run on an executor.
  • tls(), PKI store support, TLS client certificates, webSocket(...) and URI endpoints for transport comfort.
  • Last Will/Testament configuration for reliable offline signaling when a client disappears unexpectedly.
  • Lifecycle callbacks for connect, disconnect and reconnect failure handling.
  • Diagnostic events for network, protocol, callback and certificate problems without forcing a logging framework on the application.
  • MQTT 5 metadata comfort for Content Type, Response Topic, Correlation Data, User Properties, Message Expiry, Topic Alias and Subscription Identifiers.
  • PLCcom result objects with quality values so applications can inspect operation outcomes consistently.

Choosing the right operation style

StyleBest forWhat to watch
Synchronous clientSimple tools, service startup code and workflows where one MQTT step naturally follows the previous step.Use sensible operation timeouts so the application does not wait forever for a broker response.
Callback subscriptionsLong-running receivers that should react immediately when the broker delivers a message.Keep callbacks short. Hand expensive work to an application executor or queue.
Async client facadeGUI applications, server processes and integrations that already compose work with CompletableFuture.Handle failed futures and cancellation paths just as carefully as successful results.
Request/responseCommand-style interactions where the requester needs the answer belonging to exactly one request.Requires MQTT 5 properties and a peer that understands the Response Topic convention.

Java 21 and newer: the client detects the runtime version automatically. On Java 21+ its internal worker threads and the default async() executor use virtual threads, so many parallel MQTT operations and many client instances become considerably cheaper. No code change is required; on Java 11 to 17 the client behaves exactly as before.

Security, persistence and reliability notes

TLS: production clients should validate the broker certificate and keep hostname verification enabled. Disabling hostname verification is useful for controlled tests, but it weakens protection against connecting to the wrong server.
Persistence: the current client runtime keeps in-flight MQTT state in memory. This is fine for many online workflows, but process restart durability requires a deliberate persistence design.
Callbacks: message callbacks should return quickly. Long-running work belongs in an application queue or executor so MQTT receive processing is not blocked unnecessarily.

Examples and workshops

Runnable client examples are maintained outside the API Javadocs in the public example repository: https://github.com/Indi-An/PLCcom-mqtt-example-java. Use them when you want complete, executable learning scenarios for connect, publish/subscribe, QoS, retained messages, request/response, JSON, TLS, WebSocket, diagnostics and MQTT 5 options.

Back to PLCcom MQTT SDK overview.

Copyright (c) Indi.An GmbH. PLCcom is a trademark of Indi.An GmbH.

Packages 
Package Description
com.plccom.mqtt.client
Public API surface for the PLCcom MQTT client.