Building Arduino Projects for the Internet of Things

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

if(distance < 700)
{
Serial.println("[INFO] Garbage Level High");


// Publish sensor data to server
publishSensorData("HIGH");
}
}


Data Publish


The fourth section of code, provided in Listing 10-3 , defines the variables, constants, and
functions that are going to be used for publishing data to an MQTT broker.
This code is a slightly modified version of MQTT publish that you developed in Chapter 3.
You do not need to make any changes for the code to work, but it is recommended that you
customize some of the messages so that they do not get mixed up with someone else using
the same values. All values that can be changed have been highlighted in bold in Listing 10-3.
If you are using your own MQTT server, make sure to change the server and port values.
The two recommended changes include the value of the topic variable and the name of
client that you need to pass while connecting to the MQTT broker.


Listing 10-3. Code for Publishing Messages to an MQTT Broker


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


void callback(char topic, byte payload, unsigned int length)
{
//Handle message arrived
}


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


void publishSensorData(String garbageLevel)
{
// Connect MQTT Broker
Serial.println("[INFO] Connecting to MQTT Broker");


if (pubSubClient.connect( "arduinoIoTClient" ))
{
Serial.println("[INFO] Connection to MQTT Broker Successful");
}
else
{
Serial.println("[INFO] Connection to MQTT Broker Failed");
}

Free download pdf