Send data using MQTT from Raspberry Pi with JAVA

Send data using MQTT from Raspberry Pi with JAVAThis is the third video in the series “IOT with Raspberry Pi” and that’s using JAVA. The series comprises of Sensor interfacing using pi4J, REST API usage with JAVA, MQTT usage with JAVA and finally adding all to the same project and running over Raspberry Pi. last two videos shows how to interface DS18B20 1 wire temperature sensor with Raspberry Pi and send data to Thingspeak by using REST API with JAVA. If you have not checked those you can do that with the links down below. This video is the 3rd in the series and is about how to publish or send sensor data using MQTT API to cloud. And in this, we are using ThingSpeak as cloud service to publish data.Publishing Data using MQTT is done using Eclipse PAHO lightweight library. MQTT is a simple lightweight publish/subscribe protocol that can be used over TCP instead of going for HTTP as MQTT is power friendly and bandwidth friendly as compared to HTTP. So it fits perfect for IOT applications. If you are interested in more about it, you can check some docs linked below.


Code:

import com.pi4j.component.temperature.TemperatureSensor;
package in.weargenius.mqtt;


import java.sql.Timestamp;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
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.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;


public class SendDataUsingMQTT{
	private MqttClient client;
	private MqttConnectOptions	conOpt;


	String brokerUrl="tcp://mqtt.thingspeak.com:1883";
	String clientId="ExamplePublish";
	String channel="channels/281567/publish/LVSBKQWJI3JL293Y";
	int qos=0;
	 public  SendDataUsingMQTT() throws MqttException {
	    	String tmpDir = System.getProperty("java.io.tmpdir");
	    	MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);

	    	try {
	    		// Construct the connection options object that contains connection parameters
	    		// such as cleanSession and LWT
		    	conOpt = new MqttConnectOptions();
		    	conOpt.setCleanSession(true);
		    	//conOpt.
	    		// Construct an MQTT blocking mode client
				client = new MqttClient(brokerUrl,MqttClient.generateClientId(), dataStore);

				// Set this wrapper as the callback handler
				
		    	client.setCallback(new MqttCallback() {
					
					@Override
					public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
						// TODO Auto-generated method stub
						String time = new Timestamp(System.currentTimeMillis()).toString();
						System.out.println("Time:\t" +time +
				                           "  Topic:\t" + arg0 +
				                           "  Message:\t" + new String(arg1.getPayload()) +
				                           "  QoS:\t" + arg1.getQos());
					}
					
					@Override
					public void deliveryComplete(IMqttDeliveryToken arg0) {
						// TODO Auto-generated method stub

			        	try {
							System.out.println(arg0.getMessageId()+" "+arg0.getMessage());
						} catch (MqttException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
					@Override
					public void connectionLost(Throwable arg0) {
						// TODO Auto-generated method stub

						System.out.println("Connection to " + brokerUrl + " lost!");

						System.out.println("Reconnecting..");
			        	try {
							client.connect(conOpt);
				        	System.out.println("Connected");
						} catch (MqttException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						//	System.exit(1);
							//client.
					}
				});
		    	if(client.isConnected()){

		        	System.out.println("was already Connected");
		        	client.disconnect();
		    	}
	        	client.connect(conOpt);
	        	System.out.println("Connected");


			} catch (MqttException e) {
				e.printStackTrace();
				System.out.println("Unable to set up client: "+e.toString());
				System.exit(1);
			}
	    		

	    	
	    }
	    public void publish(String data) throws MqttPersistenceException, MqttException{
	    	String time = new Timestamp(System.currentTimeMillis()).toString();
	    	System.out.println("Publishing at: "+time+ " to topic \""+channel+"\" qos "+qos);

	    	// Create and configure a message
	   		MqttMessage message = new MqttMessage(data.getBytes());
	    	message.setQos(qos);
	    	message.setRetained(false);

	    	client.publish(channel, message);

	    	// Disconnect the client

	    }
	    public void close() throws MqttException{    	
	    	client.disconnect();
	    	System.out.println("Disconnected");
	    }
}

Links :
Github Repo:bit.ly/2sxXweP
Code:bit.ly/2rPuRo4
Download Eclipse PAHO Library(With Dependencies):bit.ly/2srKW4B
Eclipse PAHO Website: bit.ly/2srfxPE
First Part (DS18B20 Interfacing with Raspberry Pi using JAVA): bit.ly/2rxd1WK
Second Part (Upload data to Thingspeak using REST API ): bit.ly/2rZWLMu
More on MQTT
Wikipedia:bit.ly/2shULlY
Official Website: bit.ly/2shMMp8

Java Application on Pi Playlist: bit.ly/2eB1O2K

 

You can Subscribe on YouTube by clicking this link to show your support and be updated with the latest video on the channel like this.

Subscribe: bit.ly/2d8pHge

Bikash Panda
Catch Me On

Bikash Panda

Blogger / Embedded System Developer at WeArGenius
A techie, tinkerer and tech lover, who loves to blog and feels everyone can learn tech provided they have the right attitude towards learning and passion. By profession, I am an IOT developer working in Smart Home/ Smart Grid domain.
Bikash Panda
Catch Me On

Latest posts by Bikash Panda (see all)

Bikash Panda

A techie, tinkerer and tech lover, who loves to blog and feels everyone can learn tech provided they have the right attitude towards learning and passion. By profession, I am an IOT developer working in Smart Home/ Smart Grid domain.