Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 5 ■ IOT PATTERNS: REALTIME CLIENTS


Listing 5-5. Code for Publishing an MQTT Message


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


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


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


void publishSensorData()
{
// 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");
}


// Publish to MQTT Topic
if (pubSubClient.connected())
{
Serial.println("[INFO] Publishing to MQTT Broker");
pubSubClient.publish(topic, "Intrusion Detected");
Serial.println("[INFO] Publish to MQTT Broker Complete");
}
else
{
Serial.println("[ERROR] Publish to MQTT Broker Failed");
}


pubSubClient.disconnect();
}

Free download pdf