Saturday, November 12, 2016

IOT: Install MQTT Mosquitto on Raspberry Pi and Test with various client utilities

Objective: The Objective of this tutorial is to install Mosquitto Broker on Raspberry Pi (for the OS - Raspbian Wheezy and Jessie) and test the MQTT connection using the following client utilities:
a) mosquitto-clients
b) Eclipse Paho GUI
c) Eclipse Paho Java Client


Steps to install Mosquitto Broker on Raspberry Pi:

The following are the steps to be followed to install Mosquitto Broker on Raspberry Pi:
1.     SSH to Raspberry Pi with your credentials.
2.     First things first, update your packages.
 sudo apt-get update
 sudo apt-get upgrade
 In my case, the current version of the Raspberry Pi is Jessie.
3.   Create a directory where you want to install mosquitto. This step is not mandatory. But I am creating this, so that the folders and softwares installed on raspberry Pi are better organised. Here I am planning to create a directory softwares and in that sub-folder named mosquito.
mkdir softwares
cd softwares
mkdir mosquitto
cd mosquitto

4.   Now, you need to add the Mosquitto repository. Enter the following commands.
sudo wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
sudo rm mosquitto-repo.gpg.key

5.   Next, make the repository available to apt-get. First we need to change to the apt sources list directory.
cd /etc/apt/sources.list.d/

6.   Now install the packages list for your version of Raspbian.
      For Wheezy (old version)
      sudo wget http://repo.mosquitto.org/debian/mosquitto-wheezy.list
For Jessie (latest)
sudo wget http://repo.mosquitto.org/debian/mosquitto-jessie.list
In my case, it is Jessie.

7.     Now update apt information and install Mosquitto.
 sudo apt-get update
 sudo apt-get install mosquitto mosquitto-clients
Note: The above command will install both mosquito and mosquito-clients. If you want to just install mosquito (and not the clients, then you can just use the command sudo apt-get install mosquito). Here I am installing both mosquitto and mosquitto-clients. mosquitto-clients are good to have because you can test the connectivity of your mosquito broker.

8.     Start the mosquito service with the following command:
service mosquitto status

9.      Check if the mosquito process is running with the following command
 ps -ef | grep mosquitto-jessie.list

10.  The default port that MQTT listens is 1883. So let’s check that with the following command:
netstat –tln

Now with this step, the Mosquitto is successfully installed on Raspberry Pi.
11.  To start the broker to auto run at raspberry pi start up, enter the following command:
sudo update-rc.d mosquitto defaults

Testing the MQTT Connection with client

We are now going to see how to test the MQTT connection using the following client utilities:
a) mosquitto-clients
b) Eclipse Paho GUI
c) Eclipse Paho Java Client.

a) Testing the connection with client mosquitto-clients:
Now let’s test the Broker connection using one of the MQTT client named mosquitto_pub and mosquitto_sub. These utilities come along with the MQTT Broker installation, as we did in Step 7.
mosquitto_pub is a simple MQTT version 3.1 client that will publish a single message on a topic and exit. More details can be found here.

mosquitto_sub is a simple MQTT version 3.1 client that will subscribe to a topic and print the messages that it receives. More details can be found here:
1.  In Step 7, we installed mosquitto-clients which will come with the following two utilities:
mosquitto_sub  — A command line utility for subscribing to Topics
mosquitto_pub  — A command line utility for publishing simple messages one at a time
2.  Running mosquitto_sub:
Open a terminal window (let's call A) and subscrible for the topic "hello/world"
mosquitto_sub -d -v -t hello/world
-v is for making the output verbose. This will print the Topic name as well along with the actual message payload.
Terminal A:
3.  Running mosquitto_pub:
Now open another terminal window (let's call this B) and run the mosquitto_pub to send some test messages out.
mosquitto_pub -d -t hello/world -m "Hello World"
Terminal B:
4.  Now you will see the published message "Hello World" on Terminal A.
Terminal A:

That's the end of testing the MQTT connection using mosquitto-clients.


b) Testing the connection with client Eclipse Paho GUI (RCP):
1.  There are lot of MQTT client GUI Tools available in the market and one of it is Eclipse Paho GUI.
2.  The following 3 GUI tools are provided by Eclipse Paho:
·         RCP application. Can run standalone or in the Eclipse IDE.
·         Eclipse plugin. Not all the features of the Java API are included.
·         Java Swing application (IA92 replacement).
Here I am going to install the first one, i.e RCP application for this tutorial. In my case, I want to install this on Windows laptop, so going to download Windows 64-bit link provided or directly click the below link and download the zip file (by selecting the closest mirror).
http://repo.eclipse.org/content/repositories/paho-releases/org/eclipse/paho/org.eclipse.paho.ui.app/1.0.0/org.eclipse.paho.ui.app-1.0.0-win32.win32.x86_64.zip
I am going to run this standalone. So just unzip the zip file to any folder and click "paho" Application file, which will open the Paho GUI client.

3.  Now click the + button on the top right corner to add a new connection to enter you
Replace the localhost with your Raspberry Pi IP address (OR the IP address of the server wherever you installed your Mosquitto broker) and click “Connect” button. Note that the port is by-default 1883 and ClientId can be retained whatever the Paho UI has generated.

4.  Incase if you are not sure of your raspberry pi Ip address, you can use ifconfig command on the SSH terminal window and it will give you the IP Address on the screen.

5.  If your server details are correct, you will be connected successfully, as shown below. 

6. Now subscribe to a new topic by clicking the + icon and enter the Topic name hello/world and click “Subscribe” button, which indicates that you are subscribing for the topic hello/world

7. Now publish some message (let’s say “Message from Eclipse Paho”) to the topic hello/world by clicking the “Publish” button.

In the History tab, you will see the message that is both Published and Received.

If you still have the Terminal A window (from step 13 above) still open, you will see the below message even there.


    c) Testing the connection with client Eclipse Paho Java Client:

The Paho Java Client is an MQTT client library written in Java for developing applications that run on the JVM or other Java compatible platforms such as Android.

The Paho Java Client provides two APIs: MqttAsyncClient provides a fully asychronous API where completion of activities is notified via registered callbacks. MqttClient is a synchronous wrapper around MqttAsyncClient where functions appear synchronous to the application.
1.  Now we are going to see how to write a Java MQTT Client code using Eclipse Paho, which will connect to MQTT Broker and publish a message to the topic hello/world.
2.     Now connect to Raspberry Pi using SSH and with your login credentials.
3.     Now git clone your code. In my case, the command is:
git clone https://github.com/agilerules/IOT.git

Note: The explanation of the code can be found in the below section.
4.   Once the git clone is complete, you will see IOT folder created. Now go to IOT folder (using the command cd IOT) and you will see the folder Utilities inside this folder IOT. You can ignore the other sub-folders for this demo.
5.   Move to this Utilities folder (using the command cd Utilities)
6.   Now before running this Java class, let’s open a new Terminal Window by connecting to Raspberry via SSH and let’s subscribe to topic “hello/world” using mosquitto_sub utility (another MQTT Client, which we installed before) with the following steps:
Open a terminal window and subscribe for the topic "hello/world"
mosquitto_sub -d -v -t hello/world
-v is for making the output verbose. This will print the Topic name as well along with the actual message payload.
7.   Now execute the following command to start the maven build. (Incase if mvn command is not recognized then it means that maven is not installed on your Raspberry Pi.  Please follow my tutorial on how to install Maven on Raspberry Pi.)
mvn exec:java -Dexec.mainClass="com.agilerules.demo.MqttPublishSample"

8.   Finally, you should see the System.out.println() messages from our MqttPublishSample.java, as shown below, which indicates that the Java classes has run and connected to our MQTT broker and successfully published the message “Message from MqttPublishSample” to the topic hello/world.
9.   If you still have the terminal window [in step 4 above in the section a) Testing the connection with client mosquitto-clients] open, you will see the below message “Message from MqttPublishSample” even there.

This concludes that the Eclipse Paho Java client testing is working fine.

Code Explanation:
Pom.xml
10.  Since the Paho MQTT code isn't in Maven Central, we need to include its repository in the pom.xml using the following way:
<repositories>
      <repository>
            <id>Eclipse Paho Repo</id>
            <name>Paho MQTT Client</name>
            <url>https://repo.eclipse.org/content/repositories/paho-releases/</url>
      </repository>
</repositories>
Note: You can also use the Nightly snapshots URL, if required and here is the URL:
https://repo.eclipse.org/content/repositories/paho-snapshots/
11. Here is the dependency for Eclipse Paho.
  <dependencies>
      <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.0.1</version>
      </dependency>
   </dependencies>
Note: I am using the version 1.0.1. You can modify the version whatever you want.

12.   Here is the complete structure of the pom.xml
MqttPublishSample.java
13 This Java sample is a client code which will connect to MQTT Broker and publish a message to the topic hello/world.

14. The following are the inputs that are required for the client to connect to broker and publish the message. The inputs are - like what should be topic (hello/world) I am in interested in, what message to be published, what should be the Quality of Service (qos) – 2 during the connection, what is the broker URL and Client Id.
15.    The following are the steps for Eclipse Paho client to connect to Broker and publish the message:
-MqttClient instance to be initialized with the inputs like broker, ClientId and Persistence.
-MqttConnectOptions to be initialized to set Clean Session by passing boolean true
-Connect to the client using mqttClient.connect() method
-Publish a message to the client by providing the message content, setting the Quality of Service (QOS) and publish the message to the topic (hello/world)
-Finally disconnect from the client using mqttClient.disconnect() method



No comments:

Post a Comment