Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 11 ■ IOT PATTERNS: MACHINE TO MACHINE


else
{
publishSensorData("HIGH");
}
Serial.println("-----------------------------------------------");
}


Data Publish


The fourth section of the code defines the variables, constants, and functions that are
going to be used for publishing data to an MQTT broker (for details, see Chapter 3 ).
This code is similar to what you saw in Chapter 3. There are a few changes that you
need to make. All the changes are highlighted in bold in Listing 11-3. Make sure to change
the server , port , and topic variables and the name of client that you need to pass while
connecting to the MQTT broker. The other main change includes an IF/ELSE condition
that publishes different messages based on the lightLevel parameter passed by the
readSensorData() function.


Listing 11-3. Code for Publishing an MQTT Message


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


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


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


void publishSensorData( String lightLevel )
{
// 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