Monday, 30 November 2020

Configuring and running the Paho-MQTT C++ using Eclipse and Mosquitto broker

 

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:

  1. Asynchronous communication in near real-time between many different devices.
  2. Works on lossy and unreliable networks, such as a mobile connection
  3. Very low network overhead functions over TCP/IP
  4. Follows a publish/subscribe paradigm, allowing a single unit to emit messages to many listeners
  5. 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 broker

To work within this model, a client should be able to execute five commands.

  1. Connect – Connect to a broker, utilize a keep-alive if real-time notification required
  2. Subscribe – Register yourself with the broker to listen for a message on a specific topic
  3. Publish – Post a message to a specific topic
  4. Unsubscribe – Remove your subscription to a specific topic
  5. Disconnect – Disconnect from a broker

Pre-requisites

  1. This procedure was tested on Ubuntu 20.04 LTS.
  2. 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 3

In 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

$ cd eclipse-workspace/MQTT-tutorial

$ make

$ bin/publisher

Like in exercise 1, run the following commands (identified with a '$') in each terminal as shown in Figure 9.

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!' <NOT USED>


Figure 9: commands to run in each terminal


 

Figure 10: Results obtained while running the publisher 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 <thread>	// For sleep
#include <atomic>
#include <chrono>
#include <cstring>
#include "mqtt/async_client.h"

using namespace std;

const std::string DFLT_SERVER_ADDRESS	{ "tcp://localhost:1883" };
const std::string DFLT_CLIENT_ID		{ "eclipse_publisher" };

const string TOPIC { "topic2" };

const char* PAYLOAD1 = "Hello from publisher 1 (Eclipse terminal)!";
const char* PAYLOAD2 = "Hi there!";
const char* PAYLOAD3 = "Is anyone listening?";
const char* PAYLOAD4 = "Someone is always listening.";

const char* LWT_PAYLOAD = "Last will and testament.";

const int  QOS = 1;

const auto TIMEOUT = std::chrono::seconds(10);
  • 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_publisher"); is used to define the name of the publisher.
  • const std::string TOPIC("topic2"); is used to define the topic name (topic2).
  • const int QOS = 1; defines the Quality of Services parameter;
  • const auto TIMEOUT = std::chrono::seconds(10); specifies the number of attempts to connect to the broker.
  • const char* PAYLOAD1, const char* PAYLOAD2, const char* PAYLOAD3, const char* PAYLOAD4; defines the payloads to be sent to the subscribers.
  • const char* LWT_PAYLOAD; is used to test the connection with the broker;

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.

/**
 * A derived action listener for publish events.
 */
class delivery_action_listener : public action_listener
{
	atomic<bool> done_;

	void on_failure(const mqtt::token& tok) override {
		action_listener::on_failure(tok);
		done_ = true;
	}

	void on_success(const mqtt::token& tok) override {
		action_listener::on_success(tok);
		done_ = true;
	}

public:
	delivery_action_listener() : done_(false) {}
	bool is_done() const { return done_; }
};

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,

int main(int argc, char* argv[])
{
	string	address  = (argc > 1) ? string(argv[1]) : DFLT_SERVER_ADDRESS,
			clientID = (argc > 2) ? string(argv[2]) : DFLT_CLIENT_ID;

	cout << "Initializing for server '" << address << "'..." << endl;
	mqtt::async_client client(address, clientID);

	callback cb;
	client.set_callback(cb);

	mqtt::connect_options conopts;
	mqtt::message willmsg(TOPIC, LWT_PAYLOAD, 1, true);
	mqtt::will_options will(willmsg);
	conopts.set_will(will);

	cout << "  ...OK" << endl;

	try {
		cout << "\nConnecting..." << endl;
		mqtt::token_ptr conntok = client.connect(conopts);
		cout << "Waiting for the connection..." << endl;
		conntok->wait();
		cout << "  ...OK" << endl;

		// First use a message pointer.

		cout << "\nSending message..." << endl;
		mqtt::message_ptr pubmsg = mqtt::make_message(TOPIC, PAYLOAD1);
		pubmsg->set_qos(QOS);
		client.publish(pubmsg)->wait_for(TIMEOUT);
		cout << "  ...OK" << endl;

		// Now try with itemized publish.

		cout << "\nSending next message..." << endl;
		mqtt::delivery_token_ptr pubtok;
		pubtok = client.publish(TOPIC, PAYLOAD2, strlen(PAYLOAD2), QOS, false);
		cout << "  ...with token: " << pubtok->get_message_id() << endl;
		cout << "  ...for message with " << pubtok->get_message()->get_payload().size()
			<< " bytes" << endl;
		pubtok->wait_for(TIMEOUT);
		cout << "  ...OK" << endl;

		// Now try with a listener

		cout << "\nSending next message..." << endl;
		action_listener listener;
		pubmsg = mqtt::make_message(TOPIC, PAYLOAD3);
		pubtok = client.publish(pubmsg, nullptr, listener);
		pubtok->wait();
		cout << "  ...OK" << endl;

		// Finally try with a listener, but no token

		cout << "\nSending final message..." << endl;
		delivery_action_listener deliveryListener;
		pubmsg = mqtt::make_message(TOPIC, PAYLOAD4);
		client.publish(pubmsg, nullptr, deliveryListener);

		while (!deliveryListener.is_done()) {
			this_thread::sleep_for(std::chrono::milliseconds(100));
		}
		cout << "OK" << endl;

		// Double check that there are no pending tokens

		auto toks = client.get_pending_delivery_tokens();
		if (!toks.empty())
			cout << "Error: There are pending delivery tokens!" << endl;

		// Disconnect
		cout << "\nDisconnecting..." << endl;
		conntok = client.disconnect();
		conntok->wait();
		cout << "  ...OK" << endl;
	}
	catch (const mqtt::exception& exc) {
		cerr << exc.what() << endl;
		return 1;
	}

 	return 0;
}

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