Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 11 ■ IOT PATTERNS: MACHINE TO MACHINE

Listing 11-5. Code for Including External Dependencies


#include <SPI.h>
#include <WiFi.h>
#include <PubSubClient.h>


Internet Connectivity (Wireless)


The second section of the code defines the variables, constants, and functions that are
going to be used for connecting to the Internet. Use the code from Listings 2-7, 2-8, and
2-9 (in Chapter 2 ) here.


Data Subscribe


The third section of code defines the variables, constants, and functions that are going to
be used for connecting to an MQTT broker and callback when a new message arrives (for
details, see Chapter 3 ).
This code is similar to what you saw in Chapter 3. There are only few changes that
you need to make for the code to work. All changes have been highlighted in bold in
Listing 11-6. Make sure to change the server , port , and topic variable values to your
MQTT server’s values.
Whenever a new message is received, the callback(...) function is called. It
extracts the payload and calls the turnLightsOnOff() function. One addition to this code
is the IF/ELSE condition, which checks for the value of the payloadContent and if it is
LOW, sends ON as the parameter to the turnLightsOnOff(...) function. Otherwise, OFF is
sent as the parameter.


Listing 11-6. Code for Subscribing to an MQTT Broker


// IP address of the MQTT broker
char server[] = {"iot.eclipse.org"};
int port = 1883;
char topic[] = {"codifythings/lightlevel"};


PubSubClient pubSubClient(server, port, callback, client);


void callback(char topic, byte payload, unsigned int length)
{
// Print payload
String payloadContent = String((char *)payload);
Serial.println("[INFO] Payload: " + payloadContent);


if(payloadContent.substring(0,3) == "LOW")
{
// Turn lights on/off
turnLightsOnOff("ON");
}

Free download pdf