How to connect to Losant MQTT broker with Java


#1

Here’s an example of connecting and publishing state data to the Losant MQTT broker with the Eclipse Paho Client. Refer to Losant’s MQTT documentation for full specification details. This example is using hard-coded JSON. In reality, you’d probably want to also include a JSON library like Google’s gson library to generate the actual state payloads.

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttPublishSample {

public static void main(String[] args) {

    String broker  = "ssl://broker.losant.com:8883";
    String deviceId  = "your-device-id";
    String accessKey = "your-access-key";
    String accessSecret = "your-access-secret";

    MemoryPersistence persistence = new MemoryPersistence();


    try {
        MqttClient sampleClient = new MqttClient(broker, deviceId, persistence);

        // Connection Options
        // Losant access key is MQTT username.
        // Losant access secret is MQTT password.
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setUserName(accessKey);
        connOpts.setPassword(accessSecret.toCharArray());

        // Connect to broker.
        sampleClient.connect(connOpts);

        // Example state payload (JSON)
        // { "data" : { "temperature" : 24 }}
        // Replace "temperature" with your actual device attributes.
        // Add additional properties under the "data" object for each attribute on your device.
        String payload = "{ \"data\" : { \"temperature\" : \"24\" }}";

        MqttMessage message = new MqttMessage();
        message.setQos(1);
        message.setPayload(payload.getBytes());

        // Publish state to Losant broker. Topic is "losant/your-device-id/state".
        sampleClient.publish("losant/" + deviceId + "/state", message);

        sampleClient.disconnect();
        System.exit(0);

    } catch(MqttException me) {
        System.out.println("reason "+me.getReasonCode());
        System.out.println("msg "+me.getMessage());
        System.out.println("loc "+me.getLocalizedMessage());
        System.out.println("cause "+me.getCause());
        System.out.println("excep "+me);
        me.printStackTrace();
    }
}}