Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 5 ■ IOT PATTERNS: REALTIME CLIENTS


Android Studio will generate an empty class file with the default code , as shown in
Listing 5-17.


Listing 5-17. Default Code for MQTTClient.java


public class MQTTClient
{
...
}


Next you are going to add code to the MQTTClient that will connect and subscribe to an
MQTT broker, and whenever a new message is received to the subscribed topic, code will
update the app’s user interface. Listing 5-18 provides the complete code for MQTTClient.


Listing 5-18. Complete Code of MQTTClient.java


package com.codifythings.intrusiondetectionsystem;


import android.util.Log;


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.persist.MemoryPersistence;


import java.text.DateFormat;
import java.util.Date;


public class MQTTClient {
private static final String TAG = "MQTTClient";
private String mqttBroker = "tcp://iot.eclipse.org:1883";
private String mqttTopic = "codifythings/intrusiondetection";
private String deviceId = "androidClient";


// Variables to store reference to the user interface activity.
private MainActivity activity = null;


public MQTTClient(MainActivity activity) {
this.activity = activity;
}


public void connectToMQTT() throws MqttException {
// Request clean session in the connection options.
Log.i(TAG, "Setting Connection Options");
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);

Free download pdf