Introduction to MQTT

Pages
Contributors: Alex the Giant
Favorited Favorite 15

Setting Up the Broker

There's a large collection of MQTT brokers available that can run from a remote server, or locally, both on your office machine as well as a dedicated computer like a Raspberry Pi. In the example used in this tutorial, we're going to use a Raspberry Pi connected to our local network running a free and open-source broker called Mosquitto.

Setting up Mosquitto is simple, just open your terminal and enter:

language:bash
sudo apt-get install mosquitto -y

Once installed, we'll want to make sure our broker is working by correctly by creating a test client from the Pi to listen to a topic. We'll do this by installing the mosquitto clients:

language:bash
sudo apt-get install mosquitto mosquitto-clients -y

Once the clients have been installed, we'll subscribe to the topic "test_topic" by entering:

language:bash
mosquitto_sub -t "test_topic"

We're telling mosquitto we'd like to subscribe to a topic by entering mosquitto_sub, and that we'd like to subscribe to a topic denoted by -t with the name test_topic. Now every time we publish to test_topic, the message sent will appear in this window.

Because our terminal is listening for messages from our broker, we'll need to open a second terminal window to publish messages to. Once opened, we'll publish to test_topic with the following command:

language:bash
mosquitto_pub -t "test_topic" -m "HELLO WORLD!"

Just like before, we use the -t to denote the topic, but this time we're adding a message to publish to the topic by using mosquitto_pub and using -m to denote the message to we'd like to publish. Once we hit enter, we should see our message appear on subscriber terminal window as shown below. You can replace that text with any string you'd like after -m to send your message to all of the clients subscribed to test_topic.

Hello World Example