Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Hands-On MQTT Programming with Python
Hands-On MQTT Programming with Python

Hands-On MQTT Programming with Python: Work with the lightweight IoT protocol in Python

Arrow left icon
Profile Icon Gaston C. Hillar
Arrow right icon
Can$27.98 Can$39.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3 (3 Ratings)
eBook May 2018 228 pages 1st Edition
eBook
Can$27.98 Can$39.99
Paperback
Can$49.99
Subscription
Free Trial
Arrow left icon
Profile Icon Gaston C. Hillar
Arrow right icon
Can$27.98 Can$39.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3 (3 Ratings)
eBook May 2018 228 pages 1st Edition
eBook
Can$27.98 Can$39.99
Paperback
Can$49.99
Subscription
Free Trial
eBook
Can$27.98 Can$39.99
Paperback
Can$49.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Hands-On MQTT Programming with Python

Using Command-Line and GUI Tools to Learn How MQTT Works

In this chapter, we will work with command-line and GUI tools to learn how MQTT 3.1.1 works in detail. We will learn MQTT basics, the specific vocabulary for MQTT, and its working modes. We will use different utilities and diagrams to understand the most important concepts related to MQTT. We will understand everything we need to know before writing Python code to work with the MQTT protocol. We will work with the different Quality of Service (QoS) levels and we will analyze and compare their overheads. We will gain an understanding of the following:

  • Subscribing to topics with a command-line tool
  • Subscribing to topics with a GUI tool
  • Publishing messages with a command-line tool
  • Publishing messages with a GUI tool
  • Unsubscribing from topics with a GUI tool
  • Learning best practices for topics
  • Understanding MQTT wildcards
  • Learning...

Subscribing to topics with a command-line tool

A drone is an IoT device that interacts with many sensors and actuators, including digital electronic speed controllers linked to engines, propellers, and servomotors. A drone is also known as an unmanned aerial vehicle (UAV), but we will definitely refer to it as a drone. Let's imagine that we have to monitor many drones. Specifically, we have to display their altitude and the speed for each of their servomotors. Not all of the drones have the same number of engines, propellers, and servomotors. We have to monitor the following types of drone:

Name Number of propellers
Quadcopter 4
Hexacopter 6
Octocopter 8

Each drone will publish its altitude every 2 seconds to the following topic: sensors/dronename/altitude, where dronename must be replaced by the name assigned to each drone. For example, the drone named octocopter01...

Subscribing to topics with a GUI tool

MQTT.fx is a GUI utility implemented with JavaFX that is available for Windows, Linux, and macOS. This tool allows us to connect with an MQTT server, subscribe to topic filters, see received messages, and publish messages to topics. You can download the appropriate version for your operating system from the downloads section of the main web page for this utility: http://www.mqttfx.org.

Now, we will use the MQTT.fx GUI utility to generate another MQTT client that subscribes to the same topic, sensors/octocopter01/altitude, and displays all the messages it receives. We will work with MQTT.fx version 1.6.0. Follow these steps:

  1. Launch MQTT.fx, select local mosquitto in the dropdown located at the upper-left corner, and click on the configuration icon at the right-hand side of this dropdown and at the left-hand side of the Connect button. MQTT...

Publishing messages with a command-line tool

We will use the mosquitto_pub command-line utility included in Mosquitto to generate a simple MQTT client that publishes a message to a topic. Open a Terminal in macOS or Linux, or a Command Prompt in Windows, go to the directory in which Mosquitto is installed, and run the following command:

mosquitto_pub -V mqttv311 -t sensors/octocopter01/altitude -m  "25 f" -d

The previous command will create an MQTT client that will establish a connection with the local MQTT server and then will make the client publish a message to the topic specified after the -t option: sensors/octocopter01/altitude. We specify the payload for the message after the -m option: "25 f". We specify the version of the MQTT protocol that we want to use when the client establishes the connection with -V mqttv311. This way, we indicate to the MQTT...

Publishing messages with a GUI tool

Now, we will use the MQTT.fx GUI utility to generate another MQTT client that publishes another message to the same topic, sensors/octocopter01/altitude. Follow these steps:

  1. Go to the MQTT.fx window in which you established a connection and subscribed to a topic.
  2. Click Publish and enter sensors/octocopter01/altitude in the dropdown at the left-hand side of the Publish button.
  3. Enter the following text in the textbox below the Publish button: 32 f, as shown in the following screenshot:
  1. Then, click the Publish button. MQTT.fx will publish the entered text to the specified topic.

If you don't want to work with the MQTT.fx utility, you can run another mosquitto_pub command to generate another MQTT client that publishes a message to the topic. You just need to open another Terminal in macOS or Linux, or another Command Prompt in Windows...

Unsubscribing from topics with a GUI tool

Whenever we don't want a subscriber to receive more messages whose destination topic name matches one or more topic filters, the subscriber can send a request to unsubscribe to a list of topic filters to the MQTT server. Obviously, unsubscribing from topic filters is the opposite of subscribing to topic filters. We will use the MQTT.fx GUI utility to unsubscribe the MQTT client from the sensors/octocopter01/altitude topic. Follow these steps:

  1. Go to the MQTT.fx window in which you established a connection and subscribed to a topic.
  2. Click Subscribe.
  1. Click on the panel that displays the sensors/octocopter01/altitude topic name on the left-hand side of the window. Then, click on the Unsubscribe button located in this panel. The following screenshot shows this button:
  1. MQTT.fx will unsubscribe the client from the sensors/octocopter01...

Learning best practices for topics

We already know that MQTT allows us to publish messages on topics. A publisher always has to specify the topic name to which a message will be published. The easiest way to understand topic names in MQTT is to think about them as paths in a file system.

If we have to save dozens of files that have information about different types of sensor for a diverse number of drones, we can create a hierarchy of directories or folders to organize all the files that we will save. We can create a directory named sensors, then one sub-directory for each drone, such as octocopter01, and finally a sub-directory with the sensor name, such as altitude. The path in macOS or Linux will be sensors/octocopter01/altitude because these operating systems use a forward slash (/) as a delimiter. In Windows, the path will be sensors\drone\altitude because this operating...

Understanding MQTT wildcards

When we analyzed the subscription operation, we learned that an MQTT client can subscribe to one or more topic filters. If we specify a topic name as a topic filter, we will only subscribe to a single topic. We can take advantage of the following two wildcards to create topic filters that subscribe to all the topics that match the filter:

  • Plus sign (+): This is a single-level wildcard that matches any name for a specific topic level. We can use this wildcard instead of specifying a name for any topic level in the topic filter.
  • Hash (#): This is a multilevel wildcard that we can use only at the end of a topic filter, as the last level, and it matches any topic whose first levels are the same as the topic levels specified at the left-hand side of the # symbol.

For example, if we want to receive all the messages related to altitude for all the drones...

Learning about the different QoS levels

Now that we understand how connection, subscription, and publication work in combination with topic names and topic filters with wildcards, we can dive deep into the QoS levels. So far, we have analyzed how both subscription and publication work with a QoS level equal to 0. Now, we will understand what this number means and how things work when we use the other available QoS levels for publication and subscription.

Remember that publication involves publishing from the MQTT client to the MQTT server and then from the server to the subscribed client. It is very important to understand that we can publish with a QoS level and subscribe with another QoS level. Hence, there is a QoS level for the publish process between the publisher and the MQTT server and another QoS level for the publish process between the MQTT server and the subscriber...

Working with at least once delivery (QoS level 1)

First, we will use wildcards to subscribe to a topic filter with QoS level 1, and then we will publish one message to a topic name that will match the topic filter with QoS level 1. This way, we will analyze how both publishing and subscription work with QoS level 1.

We will use the mosquitto_sub command-line utility included in Mosquitto to generate a simple MQTT client that subscribes to a topic filter with QoS level 1 and prints all the messages it receives. Open a Terminal in macOS or Linux, or a Command Prompt in Windows, go to the directory in which Mosquitto is installed, and run the following command:

mosquitto_sub -V mqttv311 -t sensors/+/altitude -q 1 -d

The previous command will create an MQTT client that will establish a connection with the local MQTT server and then will make the client subscribe to the topic filter...

Working with exactly once delivery (QoS level 2)

First, we will use wildcards to subscribe to a topic filter with QoS level 2, and then we will publish one message to a topic that will match the topic filter with QoS level 2. This way, we will analyze how both publishing and subscription work with QoS level 2.

We will use the mosquitto_sub command-line utility included in Mosquitto to generate a simple MQTT client that subscribes to a topic filter with QoS level 1 and prints all the messages it receives. Open a Terminal in macOS or Linux, or a Command Prompt in Windows, go to the directory in which Mosquitto is installed, and run the following command:

mosquitto_sub -V mqttv311 -t sensors/quadcopter30/# -q 2 -d

The previous command will create an MQTT client that will establish a connection with the local MQTT server and then will make the client subscribe to the topic filter...

Understanding overhead in the different Quality of Service levels

The following diagram summarizes the different packages that are exchanged between an MQTT client and an MQTT server to publish a message with QoS levels 0, 1, and 2. This way, we can easily recognize the increased overhead as we increase the QoS level:

It is very important to take into account the additional overhead required by QoS level 2 and to use it only when it is really necessary.

Test your knowledge

Let's see whether you can answer the following questions correctly:

  1. QoS level 0 for MQTT means:
    1. Exactly once delivery
    2. At most once delivery
    3. At least once delivery
  2. QoS level 1 for MQTT means:
    1. Exactly once delivery
    2. At most once delivery
    3. At least once delivery
  3. QoS level 2 for MQTT means:
    1. Exactly once delivery
    2. At most once delivery
    3. At least once delivery
  4. If the application isn't able to tolerate duplicates and we have to make sure that the messages reach the subscribers only once, the appropriate choice is:
    1. QoS level 0
    2. QoS level 1
    3. QoS level 2
  5. Which QoS level has the highest overhead:
    1. QoS level 0
    2. QoS level 1
    3. QoS level 2

The rights answers are included in the Appendix, Solutions.

Summary

In this chapter, we worked with different tools to interact with the Mosquitto MQTT 3.1.1 server we installed in Chapter 1, Installing an MQTT 3.1.1 Mosquitto Server. We worked with an unsecured MQTT server to easily understand the interaction between the MQTT clients and the MQTT server.

We subscribed to topics via the command-line and GUI tools. Then, we published messages with QoS level 0 and we unsubscribed from topics. We learned best practices related to topics; and single-level, and multilevel wildcards. We studied in detail the different Quality of Service levels supported by MQTT and when it is appropriate to use each of them. We analyzed their advantages and disadvantages.

Now that we understood how the MQTT 3.1.1 basics work, we will learn how to secure an MQTT server and to follow best practices related to security, which are the topics that we are going to...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • <ul><li>Make your connected devices less prone to attackers by understanding security mechanisms</li>
  • <li>Take advantage of MQTT features for IoT and Machine-to-Machine communications</li>
  • <li>The only book that covers MQTT with a single language, Python</li>
  • </ul>

Description

<p>MQTT is a lightweight messaging protocol for small sensors and mobile devices. This book explores the features of the latest versions of MQTT for IoT and M2M communications, how to use them with Python 3, and allow you to interact with sensors and actuators using Python.</p> <p>The book begins with the specific vocabulary of MQTT and its working modes, followed by installing a Mosquitto MQTT broker. You will use different utilities and diagrams to understand the most important concepts related to MQTT. You will learn to make all the necessary configuration to work with digital certificates for encrypting all data sent between the MQTT clients and the server. You will also work with the different Quality of Service levels and later analyze and compare their overheads.</p> <p>You will write Python 3.x code to control a vehicle with MQTT messages delivered through encrypted connections (TLS 1.2), and learn how leverage your knowledge of the MQTT protocol to build a solution based on requirements. Towards the end, you will write Python code to use the PubNub cloud-based real-time MQTT provider to monitor a surfing competition.</p> <p>In the end, you will have a solution that was built from scratch by analyzing the requirements and then write Python code that will run on water-proof IoT boards connected to multiple sensors in surfboards.</p>

Who is this book for?

<p>This book is for developers who want to learn about the MQTT protocol for their IoT projects. Prior knowledge of working with IoT and Python will be helpful.</p>

What you will learn

  • <ul><li>Learn how MQTT and its lightweight messaging system work</li>
  • <li>Understand the MQTT puzzle: clients, servers (formerly known as brokers), and connections</li>
  • <li>Explore the features included in the latest versions of MQTT for IoT and M2M communications</li>
  • <li>Publish and receive MQTT messages with Python</li>
  • <li>Learn the difference between blocking and threaded network loops</li>
  • <li>Take advantage of the last will and testament feature</li>
  • <li>Work with cloud-based MQTT interfaces in Python</li>
  • </ul>

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 22, 2018
Length: 228 pages
Edition : 1st
Language : English
ISBN-13 : 9781789137811
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : May 22, 2018
Length: 228 pages
Edition : 1st
Language : English
ISBN-13 : 9781789137811
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 161.97
Hands-On Internet of Things with MQTT
Can$55.99
MQTT Essentials - A Lightweight IoT Protocol
Can$55.99
Hands-On MQTT Programming with Python
Can$49.99
Total Can$ 161.97 Stars icon

Table of Contents

8 Chapters
Installing an MQTT 3.1.1 Mosquitto Server Chevron down icon Chevron up icon
Using Command-Line and GUI Tools to Learn How MQTT Works Chevron down icon Chevron up icon
Securing an MQTT 3.1.1 Mosquitto Server Chevron down icon Chevron up icon
Writing Code to Control a Vehicle with Python and MQTT Messages Chevron down icon Chevron up icon
Testing and Improving Our Vehicle Control Solution in Python Chevron down icon Chevron up icon
Monitoring a Surfing Competition with Cloud-Based Real-Time MQTT Providers and Python Chevron down icon Chevron up icon
Solutions Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3
(3 Ratings)
5 star 0%
4 star 33.3%
3 star 0%
2 star 33.3%
1 star 33.3%
LAURENT Feb 12, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Really good book ! Easy to understand (clear examples and no errors as far as i can see)Will definitely buy another version if author can make a longer chapter on multithreading (a bit short in this book) and an introduction to another mqtt server (as vernemq for example) for shared subscriptions and clustering (not present on mosquitto).
Amazon Verified review Amazon
Kurt Keller Jul 18, 2019
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
There are good things about this book and not so good things. At around 200 pages, the book is not too big. It is easy to read, kept in understandable language. But at this page count, it feels overly repetitive: "We are going to see how to do X", "To do X do X.1", "To do X do X.2", "To do X, do X.3", "We have seen how to do X".The story used in the book to go along is about monitoring and/or controlling drones, small vehicles or surfboards. But it does not require you to actually own one of the boards or devices mentioned, everything is kept in 'simulation mode' and can be run on a PC.What I definitely like about the book is, that it shows you how to perform everything you need to follow along. The author does not assume that you know how to install a Mosquitto server or how to setup a venv environment in Python, or how to create self signed SSL certificates. He explains all these steps detailed in an easy to follow way for those readers who may not be familiar with these tasks. So to follow along, you don't really need to know much, you'll really be guided well through everything required. Before the book starts with the actual programming (after more than half the page count), it does explain MQTT and shows how it works and how to use it. So it is, in my opinion, mostly a book about MQTT and explains how this protocol works and how to use it with Python code. If your main goal is to learn about MQTT, a good choice.If you are more interested in how to write Python code interacting with MQTT, rather than how MQTT works, then I would not really recommend this book. I am not a professional programmer, but neither is Python something new for me. Although the code presented and built step by step does work, it is, in my opinion, quite flawed. Connections to the MQTT server are stored as class variables, rather than instance variables (which I still could see as useful in certain specific situations); class methods are declared as static methods (normally used if the method does not need anything from the class) but then access things in the class by referencing the class name; a method is created which builds a non-changing dictionary from scratch each time the method is called... Again, I am not a professional programmer, but to me the code looks like a mess. Personally, I only used a few lines from it, had a look at the paho.mqtt.client help and successfully and quickly built my project in a way I think is more sensible.You want an introduction to MQTT and/or the Mosquitto Server? This book is OK for you. You want to learn how to write Python code accessing an MQTT server? Don't use this book.
Amazon Verified review Amazon
Ben de Leur Jun 21, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
The table of contents states that a class will be made to control a motor via mqttThis was the reason for me to buy this bookIt appears to be a dummy class with only stubs ...Total scams
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.