Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 5 ■ IOT PATTERNS: REALTIME CLIENTS


// Update the screen with newly received message.
activity.updateView(sensorMessage);
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
}
}
}


In Listing 5-18 , variable TAG will be used while logging so that you can identify your
app’s messages in the log.
The mqttBroker , mqttTopic , and deviceId variables define the MQTT broker your
app will connect to, the topic that your app is subscribing to, and the device ID that will
show up on the server when your app successfully connects.
The activity variable is defined to store a reference of user interface activity so that
you can directly make updates.
The code for connecting and subscribing to the MQTT broker goes in the
connectToMQTT() method. Initialize a new MqttClient and connect it to the iot.
eclipse.org:1883 server with a clean session. You need to execute your code whenever
a new message is published to the codifythings/intrusiondetection queue, so first
set the callback method by providing a new instance of MqttEventCallback and then
subscribe to the topic codifythings/intrusiondetection.
Once you subscribe to a topic and set a callback method , the MQTT library will
always call your MqttCallback.messageArrived method. So now you need to provide
implementation that specifies what to do when a new message has arrived.
Your app has two requirements. It needs to create a new notification for users and
to update the screen with the latest time the activity was detected. You have already
implemented these two methods in the MainActivity class, so you are going to use the
activity reference and call the createNotification and updateView methods.
Both the screen and MQTT client are now ready, but you have not yet added the
code in the MainActivity class that actually starts the MQTTClient whenever the app
is created. So update the onCreate() method of the MainActivity class to update the
screen with an empty string and start the MQTTClient. Since you removed toolbar and
floating action button from activity_main.xml , you will need to remove the reference in
the onCreate method as well. The final code for MainActivity is provided in Listing 5-19 ,
with the changes in the onCreate() method highlighted.


Listing 5-19. Complete Code of MainActivity.java


package com.codifythings.intrusiondetectionsystem;


import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

Free download pdf