MQTT

πŸ§ͺ Lab 6 β€” The MQTT Protocol and Message Brokers

Duration: ~1 hour
Goal: Understand how to publish and subscribe to IoT messages using the MQTT protocol, and how to deploy message brokers such as EMQX and Mosquitto.


πŸ“˜ Learning Objectives

By the end of this lab, students will be able to:

  • Understand the role of MQTT in IoT communication.
  • Deploy a message broker (EMQX or Mosquitto).
  • Develop simple MQTT publisher/subscriber applications in Java using the Eclipse Paho library.
  • Test message exchange between clients via an MQTT broker.

🧩 Part 1 β€” Developing MQTT Clients

πŸ”§ Eclipse Paho Java Client

The Eclipse Paho project provides open-source MQTT client implementations for multiple platforms.
The Java client can run on any JVM-compatible environment, including Android.

πŸ“˜ More details: Paho MQTT Clients Website


βš™οΈ Step 1 β€” Install Paho Java via Maven

Add this dependency to your project’s pom.xml file:

<dependency>
  <groupId>org.eclipse.paho</groupId>
  <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
  <version>1.2.2</version>
</dependency>

πŸš€ Step 2 β€” Publish a Message

Create a Java class Publisher.java:

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class Publisher {
    public static void main(String[] args) throws Exception {
        MqttClient client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
        client.connect();

        MqttMessage message = new MqttMessage();
        message.setPayload("Hello world from Java".getBytes());

        client.publish("iot_data", message);
        System.out.println("Message published!");

        client.disconnect();
    }
}

🧠 Notes:

  • The connection URL tcp://localhost:1883 assumes your broker is running locally.
  • The topic iot_data can be replaced by any custom topic name.
  • You can explore security and QoS (Quality of Service) options via the MQTT Java Docs.

πŸ“₯ Step 3 β€” Subscribing to Receive Messages

To receive messages you need to implement a Callback class in the Subscriber application as follows:

Create a callback class SimpleMqttCallback.java:

import org.eclipse.paho.client.mqttv3.*;

public class SimpleMqttCallback implements MqttCallback {
    public void connectionLost(Throwable cause) {
        System.out.println("Connection to MQTT broker lost!");
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        System.out.println("Message received on topic '" + topic + "': " + new String(message.getPayload()));
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
        // Not used in this example
    }
}

The Callback is then used in the Subscriber application. Now create the subscriber Subscriber.java:

import org.eclipse.paho.client.mqttv3.MqttClient;

public class Subscriber {
    public static void main(String[] args) throws Exception {
        MqttClient client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
        client.setCallback(new SimpleMqttCallback());
        client.connect();

        client.subscribe("iot_data");
        System.out.println("Subscribed to topic: iot_data");
    }
}

βœ… Test:

  1. Run Subscriber.java
  2. Run Publisher.java
  3. Observe that the subscriber prints Hello world from Java when the message arrives.

🧩 Part 2 β€” Deploying Message Brokers

Now that you have publisher/subscriber clients, you need an MQTT broker to manage communication.
We’ll explore two popular options: EMQX and Mosquitto.


πŸ›°οΈ EMQX Broker

EMQX is a fully open source, highly scalable, highly available distributed MQTT messaging broker for IoT, M2M and Mobile applications that can handle tens of millions of concurrent clients.

πŸ“˜ More details: EMQX Website


🧰 Installation on Linux

Download and Install (Debian/Ubuntu)

sudo apt install ./emqx-ubuntu18.04-v4.0.0_amd64.deb
# or
sudo apt install ./emqx-debian10-v4.0.0_amd64.deb

Start and Stop EMQX

emqx start
emqx_ctl status
emqx stop

πŸ“˜ Full guide: EMQX Install Guide


🐳 Running EMQX in Docker

Pull image

docker pull emqx/emqx:v4.0.0

Run container

docker run -d --name emqx -p 1883:1883 -p 18083:18083 emqx/emqx:v4.0.0

Dashboard: http://localhost:18083
(Default credentials: admin / public)

πŸ“˜ Cluster setup: EMQX Docker Cluster Guide


βš™οΈ Setting-up the EMQX Dashboard

EMQX Broker provides a Dashboard to help users manage equipment and monitor related indicators.
Through the Dashboard, you can view:

  • Basic server information
  • Load and statistical data
  • Client connection status (and disconnect clients manually)
  • Dynamically load/unload plug-ins

In addition, EMQX Dashboard also provides a visual rule engine interface, and includes a simple MQTT client tool for user testing.

πŸ“˜ Use the guide on: EMQX Dashboard to deploy the EMQX dashboard.


☁️ Setting-up the Mosquitto MQTT-based Broker

Mosquitto is an open-source message broker that uses the Message Queuing Telemetry Transport (MQTT) protocol.

πŸ“˜ More details can be found on the Mosquitto Website.


🧰 Prerequisites

  • An Ubuntu 20.04 server
  • A non-root user with sudo rights

πŸ”§ Install the Mosquitto Broker

Update the package index:

sudo apt update

Install the Mosquitto package:

sudo apt install -y mosquitto

Confirm that the service is running:

sudo systemctl status mosquitto

Manage the service (stop/start/restart):

sudo systemctl stop/start/restart mosquitto

πŸ§ͺ Install and Test the Mosquitto Clients

When using an MQTT client, you can connect to the Mosquitto broker to send/receive messages on different topics.
A client can be a publisher, a subscriber, or both.

Install the client tools:

sudo apt install -y mosquitto-clients

Subscribe to a topic

mosquitto_sub -t "home/lights/sitting_room"

Note: The above command is blocking β€” your terminal will remain in a listening state.

Publish a message (in another terminal)

mosquitto_pub -m "ON" -t "home/lights/sitting_room"
mosquitto_pub -m "OFF" -t "home/lights/sitting_room"

πŸ” Secure the Mosquitto Server

By default, the Mosquitto broker is not secured.
You can secure it by enabling authentication with username and password.

Configuration directory

Mosquitto reads configuration files from:

/etc/mosquitto/conf.d

Create a configuration file:

sudo nano /etc/mosquitto/conf.d/default.conf

Use the information below to disable anonymous connections and allow Mosquitto to read valid credentials from the /etc/mosquitto/passwd file.

Add the following lines:

allow_anonymous false
password_file /etc/mosquitto/passwd

Save and close the file.


Create user credentials

Open the password file:

sudo nano /etc/mosquitto/passwd

Add users (example):

john:EXAMPLE_PASSWORD
george:EXAMPLE_PASSWORD_2

Encrypt passwords:

Next, use the mosquitto_passwd utility to encrypt the passwords.

sudo mosquitto_passwd -U /etc/mosquitto/passwd

Verify encryption:

Your passwords are now encrypted in a format that only the Mosquitto server can decrypt. Use the Linux cat command to confirm the encryption process.

sudo cat /etc/mosquitto/passwd

Restart Mosquitto to apply changes:

sudo systemctl restart mosquitto

Connect securely using credentials

Now you must authenticate when subscribing/publishing:


From this point forward, you should execute any pub/sub command using the syntax below. Remember to replace john and EXAMPLE_PASSWORD with the credentials that you defined in the password file.

mosquitto_sub -u john -P EXAMPLE_PASSWORD -t "home/lights/sitting_room"
mosquitto_pub -u john -P EXAMPLE_PASSWORD -t "home/lights/sitting_room" -m "ON"
Previous