Actions
The ballerina/mqtt package exposes the following clients:
| Client | Purpose |
|---|---|
Client | Publish 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
| Field | Type | Default | Description |
|---|---|---|---|
serverUri | string | Required | The MQTT broker URL (e.g., tcp://localhost:1883 or ssl://broker.example.com:8883). Passed as a constructor parameter. |
clientId | string | Required | A unique client identifier for the MQTT session. Passed as a constructor parameter. |
connectionConfig | ConnectionConfiguration | () | Connection settings including authentication, TLS, reconnection, and keep-alive. |
connectionConfig.username | string | () | Username for broker authentication. |
connectionConfig.password | string | () | Password for broker authentication. |
connectionConfig.secureSocket | SecureSocket | () | SSL/TLS configuration for secure connections. |
connectionConfig.maxReconnectDelay | int | () | Maximum delay (in milliseconds) between reconnection attempts. |
connectionConfig.keepAliveInterval | int | () | Keep-alive interval in seconds. |
connectionConfig.connectionTimeout | int | () | Connection timeout in seconds. |
connectionConfig.cleanStart | boolean | () | Whether to start a clean session (discard previous session state). |
connectionConfig.serverUris | string[] | () | Fallback server URIs for high availability. |
connectionConfig.automaticReconnect | boolean | () | Whether to automatically reconnect on connection loss. |
willDetails | WillDetails | () | 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:
| Name | Type | Required | Description |
|---|---|---|---|
topic | string | Yes | The MQTT topic to publish to. |
message | mqtt:Message | Yes | The 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:
| Name | Type | Required | Description |
|---|---|---|---|
subscriptions | string|string[]|Subscription|Subscription[] | Yes | The 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();