Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 5 ■ IOT PATTERNS: REALTIME CLIENTS

// Attempt a connection to MQTT broker using the values of
// connection variables.
Log.i(TAG, "Creating New Client");
MqttClient client = new MqttClient(mqttBroker, deviceId, new
MemoryPersistence());
client.connect(options);


// Set callback method name that will be invoked when a new message
// is posted to topic, MqttEventCallback class is defined later in
// the code.
Log.i(TAG, "Subscribing to Topic");
client.setCallback(new MqttEventCallback());


// Subscribe to topic "codifythings/intrusiondetection", whenever a
// new message is published to this topic
// MqttEventCallback.messageArrived will be called.
client.subscribe(mqttTopic, 0);
}


// Implementation of the MqttCallback.messageArrived method, which is
// invoked whenever a new message is published to the topic
// "codifythings/intrusiondetection".
private class MqttEventCallback implements MqttCallback {
@ Override
public void connectionLost(Throwable arg0) {
// Do nothing
}


@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
// Do nothing
}


@Override
public void messageArrived(String topic, final MqttMessage msg)
throws Exception {
Log.i(TAG, "New Message Arrived from Topic - " + topic);


try {
// Append the payload message "Intrusion Detected"
// with "@ Current Time".
DateFormat df = DateFormat.getDateTimeInstance();
String sensorMessage = new String(msg.getPayload()) + " @ "



  • df.format(new Date());


// User is not going to be on the screen all the time,
// so create a notification.
activity.createNotification("Intrusion Detection System",
sensorMessage);

Free download pdf