MQTT Java Example

The following is an example on how to develop a simple MQTT client in Java. We use the opensource library eclipse paho which implements a MQTT layer for Java. You can use curl to download it as follows:

curl -O

You are free to use any MQTT library written in any programming language to interconnect your Things with the CloudPlugs MQTT server. Please refer to the MQTT API Overview page for additional details on our MQTT API.

Please note that MQTT topics are equivalent to CloudPlugs IoT channels.

Connecting an Existing device and Publishing Data

With a few lines of code we can connect an existing device such as a Production Thing or Controller to the CloudPlugs IoT platform and start publishing data.

Use the device’s Plug-ID and connection authentication password for cpUserName and cpPassword, respectively. If you don’t have the device’s password, you can retrieve it manually from its Production Template Enrollment Credentials panel.

1.    import org.eclipse.paho.client.mqttv3.*;
2.    // import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
4.    public class MqttPublishSample {
5.    public static void main(String[] args) {
6.                  // CloudPlugs channel or MQTT topic
7.    String topic        = "/data/"+"your_preferred_channel"; // the "/data/" prefix is mandatory to susbscribe to data. To publish data, the prefix must be "device plug-id"/data/ (e.g., dev-112233445566778899aabbcc/data/)
9.      	        // Minimum message needed, at least a JSON object with a "data" key with an associated value
10.   String content      = "{ \"data\":666 }";
12.   // QoS supported at level 0 and 1
13.   int qos             = 0;
15.   // Connection URI (ssl is also supported)
16.   String broker	    = "tcp://"; 
17.                  // Possible values ["tcp://","ssl://"]
19.   // CloudPlugs thing credentials
20.   String cpUserName = new String("dev-112233445566778899aabbcc");
21.   String cpPassword = new String("yourpassword");
23.   try {
24.   MqttClient sampleClient = new MqttClient(broker,MqttClient.generateClientId());	    
25.   MqttConnectOptions	connOpts = new MqttConnectOptions();
26.   connOpts.setCleanSession(true);
27.   connOpts.setUserName(cpUserName);
28.   connOpts.setPassword(cpPassword.toCharArray());
30.   System.out.println("[CloudPlugs]: Connecting to broker: "+broker);
31.   sampleClient.connect(connOpts);
32.          	        System.out.println("[CloudPlugs]: Connected!");
34.   System.out.println("[CloudPlugs]: Publishing message: "+content);
35.   MqttMessage message = new MqttMessage(content.getBytes());
36.       message.setQos(qos);
37.      	                sampleClient.publish(topic, message);
38.                   System.out.println("[CloudPlugs]: Message published!");
40.   sampleClient.disconnect();
41.   System.out.println("[CloudPlugs]: Disconnected");
42.          	        System.exit(0);
43.   } catch(MqttException me) {
44.   System.out.println("reason "+me.getReasonCode());
45.   System.out.println("msg "+me.getMessage());
46.   System.out.println("loc "+me.getLocalizedMessage());
47.   System.out.println("cause "+me.getCause());
48.          	        System.out.println("excep "+me);
49.          	        me.printStackTrace();
50.      	        }
51.   }
52.  }

Note that in the MQTT topic you should use the prefix “/data/” followed by the target CloudPlugs IoT channel. The topic must always contain a channel prefixed by a “/data/” string.

To publish data, you must include the Plug-ID of the publisher device at the beginning of the topic, just before “/data/” (e.g., dev-123457yyyyyyyyy/data/).

If you have enough permissions to publish data in the name of another Plug-ID (as in the case of a Controller which has WRITE permissions over a given Thing), such data will be published exactly as if it was published by the Thing Plug-ID. If the permission level is READ ONLY or DENY, the PUBLISH command will be discarded by the server and the data won’t be published.

To compile the device described above, please use the following command:

javac -cp mqtt-client-0.4.0.jar

To run it type:

java -cp mqtt-client-0.4.0.jar:. MqttPublishSample
Still need help? Get in touch!
Last updated on 29th Apr 2020