Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 6 ■ IOT PATTERNS: REMOTE CONTROL


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


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


// 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);


// Publish message to topic
Log.i(TAG, "Publishing to Topic");
MqttMessage mqttMessage =
new MqttMessage(messageContent.getBytes());
mqttMessage.setQos(2);
client.publish(mqttTopic, mqttMessage);
Log.i(TAG, "Publishing Complete");


Log.i(TAG, "Disconnecting from MQTT");
client.disconnect();
}
}


In Listing 6-9 , the variable TAG will be used while logging so that you can identify
your apps messages in the log.
The mqttBroker , mqttTopic , and deviceId variables define the MQTT broker your
app will connect to, the topic that your app will publish to, and the device ID that will
show up on the server when your app successfully connects. If you do not have an MQTT
broker installed on your machine, you can use the openly available MQTT broker from
the Eclipse Foundation.
In this project, you are only switching the state of a single light, such as from on to off
and vice versa. You are not controlling multiple lights or multiple appliances; therefore,
you do not need to create specific commands for all actions. You are going to publish the
following message whenever the user taps on the app screen.
The code for connecting and publishing to an MQTT broker goes in the
publishToMQTT() method. Initialize a new MqttClient and connect to the iot.eclipse.
org:1883 server with a clean session. Create an MqttMessage object and publish it to the

Free download pdf