Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 3 ■ COMMUNICATION PROTOCOLS


installed on your machine, you can use the openly available MQTT broker from Eclipse
Foundation ( iot.eclipse.org ) or Mosquitto ( test.mosquitto.org ).


Listing 3-7. MQTT Setup


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


As shown in Listing 3-8 , initialize the MQTT client. The callback() function
encapsulates all the details of receiving payload from broker.


Listing 3-8. MQTT Initialization and Callback Function


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


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


Standard Functions


Finally, the code in this last section is provided in Listing 3-9. It implements Arduino’s
standard setup() and loop() functions.
In the setup() function, the code initializes the serial port and connects to the
Internet. If the MQTT broker is connected, it will subscribe to the codifythings/
testMessage topic. Once successfully subscribed, the code publishes a new message to
the codifythings/testMessage topic. The code subscribes to same topic to which it is
publishing. Therefore, as soon as a message is published, the callback() function will be
called. The loop() function simply waits for new messages from the MQTT broker.


Listing 3-9. Code for Standard Arduino Functions


void setup()
{
// Initialize serial port
Serial.begin(9600);


// Connect Arduino to internet
connectToInternet();

Free download pdf