Book Image

MQTT Essentials - A Lightweight IoT Protocol

5 (1)
Book Image

MQTT Essentials - A Lightweight IoT Protocol

5 (1)

Overview of this book

This step-by-step guide will help you gain a deep understanding of the lightweight MQTT protocol. We’ll begin with the specific vocabulary of MQTT and its working modes, followed by installing a Mosquitto MQTT broker. Then, you will use best practices to secure the MQTT Mosquitto broker to ensure that only authorized clients are able to publish and receive messages. Once you have secured the broker with the appropriate configuration, you will develop a solution that controls a drone with Python. Further on, you will use Python on a Raspberry Pi 3 board to process commands and Python on Intel Boards (Joule, Edison and Galileo). You will then connect to the MQTT broker, subscribe to topics, send messages, and receive messages in Python. You will also develop a solution that interacts with sensors in Java by working with MQTT messages. Moving forward, you will work with an asynchronous API with callbacks to make the sensors interact with MQTT messages. Following the same process, you will develop an iOS app with Swift 3, build a website that uses WebSockets to connect to the MQTT broker, and control home automation devices with HTML5, JavaScript code, Node.js and MQTT messages
Table of Contents (16 chapters)
MQTT Essentials - A Lightweight IoT Protocol
About the Author
About the Reviewer
Customer Feedback

Working with WebSockets to connect to the MQTT server

The following lines declare the onConnectSuccess and connect functions within the APP.HomeAutomation.Manager object. The code file for the sample is included in the mqtt_essentials_gaston_hillar_05 folder, in the home_automation.js file:

onConnectSuccess: function(invocationContext) {
onConnectSuccess: function(invocationContext) {
        // Update the status text
        document.getElementById("status").textContent = "Connected with the MQTT Server";
        // Now, subscribe to home/results/leds/1, home/results/leds/2 and
        // home/results/leds/3
        var client = invocationContext.invocationContext.client;
        for (var i = 1; i < 4; i++) {
            client.subscribe("home/results/leds/" + i);

    connect: function() {
        this.client = new Paho.MQTT.Client(, this.port, this.clientId);
        this.client.onConnectionLost = this.onConnectionLost;