Skip to main content

Actions

The ballerina/mqtt package exposes the following clients:

ClientPurpose
ClientPublish messages to MQTT topics, subscribe to topics, and receive messages.

For event-driven integration, see the Trigger Reference.


Client

Publish messages to MQTT topics, subscribe to topics, and receive messages.

Configuration

FieldTypeDefaultDescription
serverUristringRequiredThe MQTT broker URL (e.g., tcp://localhost:1883 or ssl://broker.example.com:8883). Passed as a constructor parameter.
clientIdstringRequiredA unique client identifier for the MQTT session. Passed as a constructor parameter.
connectionConfigConnectionConfiguration()Connection settings including authentication, TLS, reconnection, and keep-alive.
connectionConfig.usernamestring()Username for broker authentication.
connectionConfig.passwordstring()Password for broker authentication.
connectionConfig.secureSocketSecureSocket()SSL/TLS configuration for secure connections.
connectionConfig.maxReconnectDelayint()Maximum delay (in milliseconds) between reconnection attempts.
connectionConfig.keepAliveIntervalint()Keep-alive interval in seconds.
connectionConfig.connectionTimeoutint()Connection timeout in seconds.
connectionConfig.cleanStartboolean()Whether to start a clean session (discard previous session state).
connectionConfig.serverUrisstring[]()Fallback server URIs for high availability.
connectionConfig.automaticReconnectboolean()Whether to automatically reconnect on connection loss.
willDetailsWillDetails()Last Will and Testament message configuration, sent by the broker if the client disconnects unexpectedly.

Initializing the client

import ballerina/mqtt;
import ballerina/uuid;

mqtt:Client mqttClient = check new (mqtt:DEFAULT_URL, uuid:createType1AsString());

Operations

Publishing

publish

Publishes a message to the specified MQTT topic.

Parameters:

NameTypeRequiredDescription
topicstringYesThe MQTT topic to publish to.
messagemqtt:MessageYesThe message to publish, including payload, QoS level, and retention flag.

Returns: mqtt:DeliveryToken|error

Sample code:

mqtt:DeliveryToken token = check mqttClient->publish("sensors/temperature", {
payload: "25.5".toBytes(),
qos: 2,
retained: true
});

Sample response:

{"messageId": 1, "topic": "sensors/temperature"}

Subscribing

subscribe

Subscribes to one or more MQTT topics. Accepts a topic string, string array, Subscription record, or Subscription array.

Parameters:

NameTypeRequiredDescription
subscriptionsstring|string[]|Subscription|Subscription[]YesThe topic(s) to subscribe to, optionally with QoS settings.

Returns: error?

Sample code:

check mqttClient->subscribe([
{topic: "sensors/temperature", qos: 2},
{topic: "sensors/humidity", qos: 1}
]);
receive

Returns a stream of messages from subscribed topics. Use this for pull-based message consumption.

Returns: stream<mqtt:Message, error?>|error

Sample code:

stream<mqtt:Message, error?> messages = check mqttClient->receive();
check from mqtt:Message msg in messages
do {
string payload = check string:fromBytes(msg.payload);
// process message
};

Sample response:

{"payload": [50, 53, 46, 53], "qos": 2, "retained": false, "duplicate": false, "messageId": 1, "topic": "sensors/temperature"}

Connection management

isConnected

Checks whether the client is currently connected to the MQTT broker.

Returns: boolean|error

Sample code:

boolean connected = check mqttClient->isConnected();

Sample response:

true
disconnect

Disconnects the client from the MQTT broker gracefully.

Returns: error?

Sample code:

check mqttClient->disconnect();
reconnect

Reconnects the client to the MQTT broker after a disconnect.

Returns: error?

Sample code:

check mqttClient->reconnect();
close

Closes the client connection and releases all resources.

Returns: error?

Sample code:

check mqttClient->close();