Back to Examples

MQTT service - SSL/TLS

The mqtt:Service receives messages from the MQTT server using the mqtt:Listener via SSL/TLS. SSL/TLS can be enabled by configuring the secureSocket, which requires a certificate or a truststore. Further, Mutual TLS (mTLS) can be enabled by providing a certificate and private key of the service or a keystore. Use this to connect to an MQTT server secured with SSL.

import ballerina/lang.value;
import ballerina/log;
import ballerina/mqtt;
import ballerina/time;

type TemperatureDetails readonly & record {
    string deviceId;
    time:Utc timestamp;
    decimal temperature;
};

listener mqtt:Listener temperatureSubscriber = new ("ssl://localhost:8883", "temperature-sub-client", "mqtt/topic", {
    connectionConfig: {
        // Provide the relevant secure socket configurations by using `mqtt:SecureSocket`.
        secureSocket: {
            cert: "./resources/path/to/public.crt"
        }
    }
});

service on temperatureSubscriber {
    remote function onMessage(mqtt:Message message) returns error? {
        TemperatureDetails details = check value:fromJsonStringWithType(check string:fromBytes(message.payload));
        log:printInfo(string `Received temperature details from device: ${details.deviceId} at
            ${time:utcToString(details.timestamp)} with temperature: ${details.temperature}`);
    }
}

Prerequisites

  • • Start an MQTT broker instance, which is configured to use SSL/TLS.

Run the program by executing the following command.

$ bal run mqtt_service_ssl.baltime=2023-08-16T16:48:03.259+05:30 level=INFO module="" message="Received temperature details from device: device-id-1 at 2023-08-16T11:18:03.212400160Z with temperature: 27.5"

Tip: Run the MQTT client given in the MQTT client - SSL/TLS example to publish some messages to the topic.

Related links

PreviousPublish message
NextBasic authentication