Messaging

The Messaging API is used initialize, connect and communicate with the ClearBlade MQTT Broker for publishing messages, subscribing, unsubscribing to and from topics and disconnect.

Please make sure that you have initialized and authenticated with the ClearBlade platform prior to using the Messaging API. This is important because the ClearBlade MQTT Broker requires the authentication token to establish a successful connection. This authentication token can only be obtained by initializing and authenticaing with the ClearBlade platform

You will need to import the following packages for using the Messaging API:
import com.clearblade.java.api.Message;
import com.clearblade.java.api.MessageCallback;

Initialize and Connect

The first step is to create a new Message object by passing the client ID and messaging QoS (optional). The Message constructor will then initialize and connect with the MQTT Broker.

String clientID = “ClearBladeJavaTest”; 
Message message = new Message(clientID); // QoS = 0 Default

OR

int qos = 1; // QoS can be 0,1 or 2
String clientID = “ClearBladeJavaTest”;  
Message message = new Message(clientID, qos);

After the connection is successful, you can publish, subscribe, unsubscribe or disconnect using the Message object.

Publish

The publish function takes a topic and message of type String and publishes to the MQTT Broker.

String topic = "yourTopic";
String message = "yourMessage";
message.publish(topic, message);

Subscribe

The subscribe function takes a topic of type String and a callback to handle the arrived messages.

String topic = "topicToSubscribe";
MessageCallback messageCallback = new MessageCallback() {
	@Override
	public void done(String topic, String messageString) {
		//Message arrived on subscribed topic
	}
};
message.subscribe(topic, messageCallback);

Unsubscribe

The unsubscribe function takes a topic of type `String.

String topic = "topicToUnsubscribe";
message.unsubscribe(topic);

Disconnect

The disconnect function is used to disconnect from the MQTT Broker. Note that this does not disconnect the user from the ClearBlade platform. User logout needs to be called separately.

message.disconnect();