Imagine you have to deploy a dozen various devices throughout a factory floor. These consist of Linux devices (i.e. PC, IoT devices, mobile phones, etc.) where each device may have one or virtual machines running and a remote database. Some devices are connected through Ethernet, while other more remote devices utilize a cell network to occasionally phone home. The problem you now have is, how do you get these devices communicating with each other in real-time? Message Queuing Telemetry Transport (MQTT) is an ISO standard protocol that can be used to solve this problem.
Introduction
Message Queuing Telemetry Transport (MQTT) is a TCP/IP based protocol designed around the following:
- Asynchronous communication in near real-time between many different devices.
- Works on lossy and unreliable networks, such as a mobile connection
- Very low network overhead functions over TCP/IP
- Follows a publish/subscribe paradigm, allowing a single unit to emit messages to many listeners
- Can encrypt data and send via TLS
These attributes make it ideal for (Machine to Machine) M2M and IoT applications. It’s especially useful where one is constrained by processing overhead, bandwidth limitations or intermittent network connections.
After a brief introduction to MQTT, this article will go over how to run an MQTT client application on your NetBurner device, and then we will create a simple application that will publish and listen for MQTT messages on a free cloud MQTT test server.
What is MQTT?
MQTT, at heart, consists of a publish/subscribe paradigm, so it is important to understand what this entails. A pub/sub model allows a single device to send data to all devices with a single packet. This is because the single device sends its data to a “broker”, which then distributes the data to all subscribers when they are available.
Figure 1: Published data distributed to multiple subscribers via a brokerTo work within this model, a client should be able to execute five commands.
- Connect – Connect to a broker, utilize a keep-alive if real-time notification required
- Subscribe – Register yourself with the broker to listen for a message on a specific topic
- Publish – Post a message to a specific topic
- Unsubscribe – Remove your subscription to a specific topic
- Disconnect – Disconnect from a broker
Pre-requisites
- This procedure was tested on Ubuntu 20.04 LTS.
- Download and Install eclipse -> C/C++ Developers.
Please clone the the MQTT-tutorial repository by open a terminal and running:
|
$ cd ~/eclipse-workspace $ git clone https://github.com/pedrombmachado/MQTT-tutorial.git |
The next IMPORTANT step is to update the virtual machine. Run the following commands
|
$ cd ~/eclipse-workspace/MQTT-tutorial $ chmod +x update.sh $ ./update.sh |
Lab work
Exercise 1 Get familiar with the environment
There are a number of MQTT brokers available for different machines. For this project, we have selected one of the most popular and stable brokers, “Mosquitto”.

Figure 2: Architecture to be implemented in exercise 1
Open terminator and right-click and select split horizontally and vertically until you get the following layout

Figure 3: exercise 1 layout
Run the following commands (identified with a '$') in each terminal as shown in Figure 3.
| Terminal 1 | Terminal 3 | Terminal 4 |
| $ mosquitto_sub -d -t 'topic1' | $ mosquitto_sub -d -t 'topic2' | $ mosquitto_sub -d -t 'topic2' |
| Terminal 2 | Terminal 5 | |
| $ mosquitto_pub -d -t 'topic1' -m 'Hello from Terminal 2!' | $ mosquitto_pub -d -t 'topic2' -m 'Hello from Terminal 5!' | |

Figure 3: commands to run in each terminal
your output will be:

Figure 4: Output
You will notice the following:
- The subscribers running in the 1st row (Terminals 1, 3, 4) will not end (i.e. they will remain connected). You can run the publishers again to test this (Terminals 2 and 5)
- The messages published by the publisher 1 (Terminal 2) will only be displayed by the subscriber 1 (Terminal 1) and the messages sent by publisher 2 (Terminal 5) will only be displayed by the 2 subscriber s (Terminals 3 and 4).
- Despite running this example on the localhost, this concept can be expanded into any machine in the network.
Exercise 2
In this exercise, we will write a subscriber in C++ to subscribe to the topic1. We will use the same layout as in exercise 1.

Figure 5: Exercise 2 architecture.
Open eclipse and localise the subscriber.cpp under the folder src. Open the Makefile and modify line 3 to NAME=subscriber. Save the Makefile and open a terminal inside eclipse and run
|
$ cd eclipse-workspace/MQTT-tutorial $ make $ bin/subscriber |
Like in exercise 1, run the following commands (identified with a '$') in each terminal as shown in Figure 6.
| Terminal 1 | Terminal 3 | Terminal 4 |
| $ mosquitto_sub -d -t 'topic1' | $ mosquitto_sub -d -t 'topic2' | $ mosquitto_sub -d -t 'topic2' |
| Terminal 2 | Terminal 5 | |
| $ mosquitto_pub -d -t 'topic1' -m 'Hello from Terminal 2!' | $ mosquitto_pub -d -t 'topic2' -m 'Hello from Terminal 5!' | |

Figure 6: commands to run in each terminal

Figure 7: Results obtained while running the subscriber in eclipse
Subscriber source code analysis
The first step is to include the required headers and the mqtt specific header "mqtt/async_client.h".
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cctype>
#include <thread>
#include <chrono>
#include "mqtt/async_client.h"
const std::string SERVER_ADDRESS("tcp://localhost:1883");
const std::string CLIENT_ID("eclipse_subcriber");
const std::string TOPIC("topic1");
const int QOS = 1;
const int N_RETRY_ATTEMPTS = 5;
|
- const string SERVER_ADDRESS { "tcp://localhost:1883" }; is used to specify the protocol (tcp), hostname or IP (in this case the localhost) and the port (1883).
- const std::string CLIENT_ID("eclipse_subcriber"); is used to define the name of the subscriber.
- const std::string TOPIC("topic1"); is used to define the topic name (topic1).
- const int QOS = 1; defines the Quality of Services parameter;
- const int N_RETRY_ATTEMPTS = 5; specifies the number of attempts to connect to the broker.
The following code is the action_listener which includes two methods one to be called if an error is detected and another to be called when a successful connection is established.
/////////////////////////////////////////////////////////////////////////////
// Callbacks for the success or failures of requested actions.
// This could be used to initiate further action, but here we just log the
// results to the console.
class action_listener : public virtual mqtt::iaction_listener
{
std::string name_;
void on_failure(const mqtt::token& tok) override {
std::cout << name_ << " failure";
if (tok.get_message_id() != 0)
std::cout << " for token: [" << tok.get_message_id() << "]" << std::endl;
std::cout << std::endl;
}
void on_success(const mqtt::token& tok) override {
std::cout << name_ << " success";
if (tok.get_message_id() != 0)
std::cout << " for token: [" << tok.get_message_id() << "]" << std::endl;
auto top = tok.get_topics();
if (top && !top->empty())
std::cout << "\ttoken topic: '" << (*top)[0] << "', ..." << std::endl;
std::cout << std::endl;
}
public:
action_listener(const std::string& name) : name_(name) {}
};
|
The action_listener includes two callbacks, on_failure is called every time that an error is detected and on_success is called when the connection is established with success.
Finally, the main function includes the code for establishing a new connection using the configuration options. Configures the procedures on how to handle errors and handle successful connections using the action_listener.
Includes also a while loop for listening to topic1 until the key "Q" or "q" is pressed. Finally, includes the procedure to disconnect from the broker.
int main(int argc, char* argv[])
{
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
callback cb(client, connOpts);
client.set_callback(cb);
// Start the connection.
// When completed, the callback will subscribe to topic.
try {
std::cout << "Connecting to the MQTT server..." << std::flush;
client.connect(connOpts, nullptr, cb);
}
catch (const mqtt::exception&) {
std::cerr << "\nERROR: Unable to connect to MQTT server: '"
<< SERVER_ADDRESS << "'" << std::endl;
return 1;
}
// Just block till user tells us to quit.
while (std::tolower(std::cin.get()) != 'q')
;
// Disconnect
try {
std::cout << "\nDisconnecting from the MQTT server..." << std::flush;
client.disconnect()->wait();
std::cout << "OK" << std::endl;
}
catch (const mqtt::exception& exc) {
std::cerr << exc.what() << std::endl;
return 1;
}
return 0;
}Exercise 3In this exercise, we will write a publisher in C++ to publish to the topic2. We will use the same layout as in exercise 1.
Figure 8: Exercise 3 architecture. Open eclipse and localise the publisher.cpp under the folder src. Open the Makefile and modify line 3 to NAME=publisher. Save the Makefile and open a terminal inside eclipse and run
Like in exercise 1, run the following commands (identified with a '$') in each terminal as shown in Figure 9.
Figure 9: commands to run in each terminal
Figure 10: Results obtained while running the publisher in eclipse Subscriber source code analysisThe first step is to include the required headers and the mqtt specific header "mqtt/async_client.h".
The following code is the delivery_action_listener which includes two methods one to be called if an error is detected and another to be called when a successful connection is established.
The delivery_action_listener includes two callbacks, on_failure is called every time that an error is detected and on_success is called when the connection is established with success. Finally, the main function includes the code for establishing a new connection using the configuration options. Configures the procedures on how to handle errors and handle successful connections using the delivery_action_listener. Includes also the sequence to publish the 4 payloads in topic2. ...OK will be printed in the screen every time that a payload is sent with success,
References[1] Netburner, available online, https://www.netburner.com/learn/mqtt-how-to-use-the-protocol-and-why-it-s-great-for-distributed-iot/, last accessed 28/11/2020 [2] Paho MQTT git repository, https://github.com/eclipse/paho.mqtt.cpp/tree/master/src/samples, last accessed 29/11/2020 |
||||||||||||||||












