MQTT Client Android tutorial for IoT future

MQTT (Message Queuing Telemetry Transport); It is a communication protocol that allows communication in the range of milliseconds between devices based on publisher and subscriber logic used in m2m technology under the Internet of things.

Mqtt technology is used as the communication protocol in the places where data is received from the sensors (such as smart home systems) where device communication is provided.

For this project, we need to have these programs:

-Android Studio
-Python

1. Dependecies

Create new app on Android Studio, then open build.gradle file and add these lines:

dependencies {
    compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
    compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
}

You will see sync button, click it.

2. Setting up cloud MQTT broker with CloudMQTT

In this tutorial, I am using CloudMQTT but there are a lot of similar MQTT Broker services on internet.

https://customer.cloudmqtt.com/login

Complete the instructions to sign up.

Next, you will be redirected to the CloudMQTT instances page. Click the + Create button to create a new CloudMQTT instance. You will access the Create new CloudMQTT instance page. Write an instance name, choose one of Data center  which is available, and make sure for the “Plan” choose the “Cute Cat”. Cause of we will use free version of that.

We have our own private cloud MQTT broker right now 🙂 . Next , we will use those credentials to connect our MQTT Android client to the broker.

3. Setting up Android Project for MQTT Client and Service

We need some permissions to use it. Thats why open your AndroidManifest.xml folder in android project and these permissons:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

And register service in android application tag:

<service android:name="org.eclipse.paho.android.service.MqttService" />

That's well, lets start to writing code. Firstly I will create MqttHelper class in my project. This class will has credentials of my mqtt server.

public class MqttHelper {
    public MqttAndroidClient mqttAndroidClient;

    final String serverUri = "tcp://m12.cloudmqtt.com:11111";

    final String clientId = "iot_demo_app";
    final String subscriptionTopic = "sensor/+";

    final String username = "yourusername";
    final String password = "yourpassword";

    public MqttHelper(Context context){
        mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean b, String s) {
                Log.w("mqtt", s);
            }

            @Override
            public void connectionLost(Throwable throwable) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                Log.w("Mqtt", mqttMessage.toString());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });
        connect();
    }

    public void setCallback(MqttCallbackExtended callback) {
        mqttAndroidClient.setCallback(callback);
    }

    private void connect(){
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());

        try {

            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {

                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                    disconnectedBufferOptions.setBufferEnabled(true);
                    disconnectedBufferOptions.setBufferSize(100);
                    disconnectedBufferOptions.setPersistBuffer(false);
                    disconnectedBufferOptions.setDeleteOldestMessages(false);
                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                    subscribeToTopic();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
                }
            });


        } catch (MqttException ex){
            ex.printStackTrace();
        }
    }


    private void subscribeToTopic() {
        try {
            mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.w("Mqtt","Subscribed!");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.w("Mqtt", "Subscribed fail!");
                }
            });

        } catch (MqttException ex) {
            System.err.println("Exceptionst subscribing");
            ex.printStackTrace();
        }
    }
}

 

So our MainActivity java class should look like this, let Android Studio resolve the imports if needed.

 

  
public class MainActivity extends AppCompatActivity {

    MqttHelper mqttHelper;
    ChartHelper mChart;
    LineChart chart;

    TextView dataReceived;
    TextView textView,textView1,textView2,olcum;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textView);
        textView1 = (TextView) findViewById(R.id.textView2);
        textView2 = (TextView) findViewById(R.id.textView3);
        olcum = (TextView) findViewById(R.id.textView5);

        dataReceived = (TextView) findViewById(R.id.dataReceived);
        chart = (LineChart) findViewById(R.id.chart);
        mChart = new ChartHelper(chart);

        startMqtt();
    }

    private void startMqtt(){
        mqttHelper = new MqttHelper(getApplicationContext());
        mqttHelper.mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean b, String s) {
                Log.w("Debug","Connected");
            }

            @Override
            public void connectionLost(Throwable throwable) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                Log.w("Debug",mqttMessage.toString());
                switch (topic.toString()){
                    case "sensor/temp":
                        dataReceived.setText(mqttMessage.toString());
                        break;
                    case "sensor/text1":
                        textView.setText(mqttMessage.toString());
                        break;
                    case "sensor/text2":
                        textView1.setText(mqttMessage.toString());
                        break;
                    case "sensor/text3":
                        textView2.setText(mqttMessage.toString());
                        break;
                    case "sensor/olcum":
                        olcum.setText(mqttMessage.toString());
                        olcum.setBackgroundColor(getResources().getColor(R.color.colorStatus));
                        break;

                        default:
                            Log.d("Error","Error ocquired");
                }

       //         dataReceived.setText(mqttMessage.toString());
                mChart.addEntry(Float.valueOf(mqttMessage.toString()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });
    }
}

I could not share activity_main.xml but you can understand how its looking:

 

4. Setting up a mock data publisher with Python

In this part, I am gonna show you for example how to read data from excel file and send it to mobile devices .

PHYTON CODE

import json
import paho.mqtt.client as mqtt
import random
import time
import threading
import sys
import xlrd
import time

mqttc = mqtt.Client("client1", clean_session=False)
mqttc.username_pw_set("yourusername", "yourpassword")
mqttc.connect("yourconnect adress", 16188, 60)
file_location = "C:\Users\Admin\Desktop\Python/test_data.xlsx"   // Download excel folder at attachment and change directory with your.
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
sheet.cell_value(0,0)
for col in range(sheet.ncols):
    time.sleep(2)
    print(sheet.cell_value(0,col))
    print(sheet.cell_value(1,col))
    print(sheet.cell_value(2,col))
    print(sheet.cell_value(3,col))
    mqttc.publish("sensor/temp", payload=sheet.cell_value(0,col), qos=0)
    mqttc.publish("sensor/text1", payload=sheet.cell_value(1,col), qos=0)
    mqttc.publish("sensor/text2", payload=sheet.cell_value(2,col), qos=0)
    mqttc.publish("sensor/text3", payload=sheet.cell_value(3,col), qos=0)
    if col == 11:
        mqttc.publish("sensor/olcum", payload="OK", qos=0)

 

 

How it looks on Mobile App

 

Thats all , sorry for the quick expression. This is my first blog post.  I will be much better in time.  🙂  I'll try to share everything that  I have learned. Don't hesitate to ask questions if you didn't understand. Thanks to everyone who is interested 🙂

Leave a reply:

Your email address will not be published.

Sliding Sidebar

A few words about me

A few words about me

Software engineer who likes weekend more than weekdays. Loves food and cooks good as well. Loves to travel and gym, can never spend a weekend sitting idle at home. Independent, modern man with a traditional heart. My actions speak more than words.

Social Profiles