Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
MQTT Essentials - A Lightweight IoT Protocol
MQTT Essentials - A Lightweight IoT Protocol

MQTT Essentials - A Lightweight IoT Protocol: Send and receive messages with the MQTT protocol for your IoT solutions.

eBook
€23.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

MQTT Essentials - A Lightweight IoT Protocol

Chapter 1. Lightweight Messaging with MQTT 3.1.1 and Mosquitto

In this chapter, we will start our journey towards the usage of the preferred IoT publish-subscribe lightweight messaging protocol in diverse IoT solutions combined with mobile apps and web applications. We will learn how MQTT and its lightweight messaging system work. 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 convenient scenarios for the MQTT protocol
  • Work with the publish-subscribe pattern
  • Work with message filtering
  • Learn basic concepts related to MQTT
  • Understand the MQTT puzzle: clients, servers or brokers, and connections
  • Install a Mosquitto MQTT server on Linux, macOS, or Windows
  • Publish messages
  • Subscribe to topics
  • Unsubscribe from topics
  • Work with best practices when creating topics
  • Understand wildcards
  • Learn about the different Quality of Service levels
  • Work with at least once delivery
  • Work with exactly once delivery

Understanding convenient scenarios for the MQTT protocol

Imagine that we have dozens of different devices that must exchange data between them. These devices have to request data to other devices and the devices that receive the requests must respond with the demanded data. The devices that requested the data must process the data received from the devices that responded with the demanded data.

The devices are Internet of Things (IoT) boards that have dozens of sensors wired to them. We have the following IoT boards with different processing powers: Raspberry Pi 3, Raspberry Pi Model B, Intel Edison, and Intel Joule 570x. Each of these boards has to be able to send and receive data. In addition, we want many mobile devices to be able to send and receive data, some of them running iOS and others Android. We have to work with many programming languages.

We want to send and receive data in near real time through the Internet and we might face some network problems, that is, our wireless networks are somewhat unreliable and we have some high-latency environments. Some devices have low power, many of them are powered by batteries and their resources are scarce. In addition, we must be careful with the network bandwidth usage because some of the devices use metered connections.

Tip

A metered connection is a network connection in which we have a limited amount of data usage per month. If we go over this amount of data, we get billed extra charges.

We can use HTTP requests and build a publish-subscribe model to exchange data between different devices. However, there is a protocol that has been specifically designed to be lighter than the HTTP 1.1 protocol and work better when unreliable networks are involved and connectivity is intermittent. The MQ Telemetry Transport (MQTT) is better suited for this scenario in which many devices have to exchange data between themselves in near real time through the Internet and we need to consume the least possible network bandwidth.

The MQTT protocol is a Machine-to-Machine (M2M) and IoT connectivity protocol. MQTT is a lightweight messaging protocol that works with a broker-based publish-subscribe mechanism and runs on top of Transmission Control Protocol / Internet Protocol (TCP/IP).

The following diagram shows the MQTT protocol on top of the TCP/IP stack:

Understanding convenient scenarios for the MQTT protocol

Note

The most popular versions of MQTT are 3.1 and 3.1.1. In this book, we will work with MQTT 3.1.1. Whenever we reference MQTT, we are talking about MQTT 3.1.1, that is, the newest version of the protocol. The MQTT 3.1.1 specification has been standardised by the OASIS consortium. In addition, MQTT 3.1.1 became an ISO standard (ISO/IEC 20922) in 2016.

MQTT is lighter than the HTTP 1.1 protocol, and therefore, it is a very interesting option whenever we have to send and receive data in near real time with a publish-subscribe model and we require the lowest possible footprint. MQTT is very popular in IoT, M2M, and embedded projects, but it is also gaining presence in web applications and mobile apps that require assured messaging and an efficient message distribution. As a summary, MQTT is suitable for the following application domains in which data exchange is required:

  • Asset tracking and management
  • Automotive telematics
  • Chemical detection
  • Environment and traffic monitoring
  • Field force automation
  • Fire and gas testing
  • Home automation
  • In-Vehicle Infotainment (IVI)
  • Medical
  • Messaging
  • Point of Sale (POS) kiosks
  • Railway
  • Radio-Frequency Identification (RFID)
  • Supervisory Control and Data Acquisition (SCADA)
  • Slot machines

As a summary, MQTT was designed to be suitable to support the following typical challenges in IoT, M2M, embedded, and mobile applications:

  • Be lightweight to make it possible to transmit high volumes of data without huge overheads
  • Distribute minimal packets of data in huge volumes
  • Support an event-oriented paradigm with asynchronous bidirectional low latency push delivery of messages
  • Easily emit data from one client to many clients
  • Make it possible to listen for events whenever they happen (event-oriented architecture)
  • Support always-connected and sometimes-connected models
  • Publish information over unreliable networks and provide reliable deliveries over fragile connections
  • Work very well with battery-powered devices or require low power consumption
  • Provide responsiveness to make it possible to achieve near real-time delivery of information
  • Offer security and privacy for all the data
  • Be able to provide the necessary scalability to distribute data to hundreds of thousands of clients

Working with the publish-subscribe pattern

Before we dive deep into MQTT, we must understand the publish-subscribe pattern, also known as the pub-sub pattern. In the publish-subscribe pattern, a client that publishes a message is decoupled from the other client or clients that receive the message. The clients don't know about the existence of the other clients. A client can publish messages of a specific type and only the clients that are interested in specific types of messages will receive the published messages.

The publish-subscribe pattern requires a broker, also known as server. All the clients establish a connection with the broker. The client that sends a message through the broker is known as the publisher. The broker filters the incoming messages and distributes them to the clients that are interested in the type of received messages. The clients that register to the broker as interested in specific types of messages are known as subscribers. Hence, both publishers and subscribers establish a connection with the broker.

It is easy to understand how things work with a simple diagram. The following diagram shows one publisher and two subscribers connected to a broker:

Working with the publish-subscribe pattern

A Raspberry Pi 3 board with an altitude sensor wired to it is a publisher that establishes a connection with the broker. An iOS smartphone and an Android tablet are two subscribers that establish a connection with the broker.

The iOS smartphone indicates to the broker that it wants to subscribe to all the messages that belong to the sensor1/altitude topic. The Android tablet indicates the same to the broker. Hence, both the iOS smartphone and the Android tablet are subscribed to the sensor1/altitude topic.

Tip

A topic is a named logical channel and it is also referred to as a channel or subject. The broker will send publishers only the messages published to topics to which they are subscribed.

The Raspberry Pi 3 board publishes a message with 100 feet as the payload and sensor1/altitude as the topic. The board, that is, the publisher, sends the publish request to the broker.

Tip

The data for a message is known as payload. A message includes the topic to which it belongs and the payload.

The broker distributes the message to the two clients that are subscribed to the sensor1/altitude topic: the iOS smartphone and the Android tablet.

Publishers and subscribers are decoupled in space because they don't know each other. Publishers and subscribers don't have to run at the same time. The publisher can publish a message and the subscriber can receive it later. In addition, the publish operation isn't synchronized with the receive operation. A publisher requests the broker to publish a message and the different clients that have subscribed to the appropriate topic can receive the message at different times. The publisher can send messages as an asynchronous operation to avoid being blocked until the clients receive the messages. However, it is also possible to send a message to the broker as a synchronous operation with the broker and to continue the execution only after the operation was successful. In most cases, we will want to take advantage of asynchronous operations.

A publisher that requires sending a message to hundreds of clients can do it with a single publish operation to a broker. The broker is responsible for sending the published message to all the clients that have subscribed to the appropriate topic. Because publishers and subscribers are decoupled, the publisher doesn't know whether there is any subscriber that is going to listen to the messages it is going to send. Hence, sometimes it is necessary to make the subscriber become a publisher too and to publish a message indicating that it has received and processed a message. The specific requirements depend on the kind of solution we are building. MQTT offers many features that make our lives easier in many of the scenarios we have been analyzing.

Working with message filtering

The broker has to make sure that subscribers only receive the messages they are interested in. It is possible to filter messages based on different criteria in a publish-subscribe pattern. We will focus on analyzing topic-based filtering, also known as subject-based filtering.

Consider that each message belongs to a topic. When a publisher requests the broker to publish a message, it must specify both the topic and the message. The broker receives the message and delivers it to all the subscribers that have subscribed to the topic to which the message belongs.

The broker doesn't need to check the payload for the message to deliver it to the corresponding subscribers; it just needs to check the topic for each message that has arrived and needs to be filtered before publishing it to the corresponding subscribers.

A subscriber can subscribe to more than one topic. In this case, the broker has to make sure that the subscriber receives the messages that belong to all the topics to which it has subscribed. It is easy to understand how things work with another simple diagram. The following diagram shows two future publishers that haven't published any messages yet, a broker and two subscribers connected to the broker:

Working with message filtering

A Raspberry Pi 3 board with an altitude sensor wired to it and an Intel Edison board with a temperature sensor wired to it will be two publishers. An iOS smartphone and an Android tablet are two subscribers that establish a connection to the broker.

The iOS smartphone indicates to the broker that it wants to subscribe to all the messages that belong to the sensor1/altitude topic. The Android tablet indicates to the broker that it wants to subscribe to all the messages that belong to any of the following two topics: sensor1/altitude and sensor42/temperature. Hence, the Android tablet is subscribed to two topics while the iOS smartphone is subscribed to just one topic.

The following diagram shows what happens after the two publishers connect and publish messages to different topics through the broker:

Working with message filtering

The Raspberry Pi 3 board publishes a message with 120 feet as the payload and sensor1/altitude as the topic. The board, that is, the publisher, sends the publish request to the broker. The broker distributes the message to the two clients that are subscribed to the sensor1/altitude topic: the iOS smartphone and the Android tablet.

The Intel Edison board publishes a message with 75 F as the payload and sensor42/temperature as the topic. The board, that is, the publisher, sends the publish request to the broker. The broker distributes the message to the only client that is subscribed to the sensor42/temperature topic: the Android Tablet. Thus, the Android tablet receives two messages.

Understanding the MQTT puzzle -- clients, servers, and connections

The MQTT broker is known as MQTT server in MQTT 3.1.1, and therefore, we will refer to it as the server. However, we must take into account that the documentation for MQTT servers, tools and client libraries can use the old MQTT broker name to refer to the server.

The MQTT server uses the previously explained topic-based filtering to filter and distribute messages to the appropriate subscribers. There are many MQTT server implementations that provide additional message filtering features by providing custom plug-ins. However, we will focus on the features that are part of the MQTT requirements.

As previously explained, in MQTT the publishers and the subscribers are completely decoupled. Publishers and subscribers are MQTT clients that only establish a connection with the MQTT server. An MQTT client can be both a publisher and a subscriber at the same time, that is, the client can publish messages to specific topics and also receive messages that belong to the topics to which the client has subscribed to.

There are MQTT client libraries available for the most popular programming languages and platforms. One of the most important things that we must consider when we select the MQTT client library is the list of MQTT features that they support and the ones that we need for our solution. Sometimes, we can choose between many libraries for a specific programming language and platform and some of them might not implement all the features. We will use many libraries for diverse programming languages and platforms throughout the book and we will learn how to evaluate whether a library is suitable or not for our needs. Specifically, we will work with Python, Java, JavaScript and Swift.

Any device that has a TCP/IP stack and is capable of using an MQTT library can become an MQTT client, that is, a publisher, a subscriber or both a publisher and a subscriber. The MQTT library makes it possible for the device to talk MQTT on top of TCP/IP and to interact with specific types of MQTT servers. For example, any of the following can become an MQTT client: an Arduino board, a Raspberry Pi 3 board, an Intel Joule board, an iPhone, an iPad, a laptop running Windows, a server running Linux, a Macbook running macOS, and Android tablet, among other devices.

There are many MQTT servers available for the most popular platforms, including Linux, Windows and macOS. Many of them are servers that can work as MQTT servers among other features. An MQTT server might implement only a subset of the MQTT capabilities and might have specific limitations. Hence, it is very important to check all the capabilities we will require in our solution before selecting an MQTT server. As happens with other middleware, we have open source versions, free versions and paid versions. Thus, we also have to make sure we select the appropriate MQTT server based on our budget and our specific needs.

Throughout this book, we will work with the Eclipse Mosquitto MQTT server (http://www.mosquitto.org). Mosquitto is an open source MQTT server with an EPL/EDL license that is compatible with MQTT versions 3.1 and 3.1.1. We can take advantage of everything we learn with any other MQTT server such as Erlang MQTT Broker (EMQ), also known as EMQTT (http://www.emqtt.io), and HiveMQ (http://hivemq.com), among others. In addition, we might use our knowledge to work with a cloud-based MQTT server such as CloudMQTT (http://www.cloudmqtt.com).

The MQTT server is the central hub of the publish/subscribe model we previously analyzed. The MQTT server is responsible of the authentication and authorization of the MQTT clients that will be able to become publishers and/or subscribers after they are authenticated and authorized. So, the first thing that an MQTT client must do is to establish a connection with the MQTT server.

In order to establish a connection, the MQTT client must send a CONNECT control packet to the MQTT server with a payload that must include all the necessary information to initiate the connection and proceed with the authentication and authorization. The MQTT server will check the CONNECT packet, perform authentication and authorization and send a response to the client with a CONNACK control packet that we will analyze in detail after understanding the CONNECT control packet. In case the MQTT client sends an invalid CONNECT control packet, the server will automatically close the connection.

The following diagram shows the interaction between an MQTT client and an MQTT server to establish a connection.

Understanding the MQTT puzzle -- clients, servers, and connections

Tip

After a successful connection has been established between an MQTT client and an MQTT server, the server will keep the connection open until the client loses the connection or sends a DISCONNECT control packet to the server to close the connection.

The CONNECT control packet must include values for the following fields in the payload and bits for a special flags byte that is included in the control packet. We want to understand the meaning of these fields and flags because we will be able to specify their values when we work with MQTT tools and MQTT client libraries.

  • ClientId: The client identifier, also known as Client ID, is a string that identifies each MQTT client that connects to an MQTT server. Each client that connects to the MQTT server must have a unique ClientId and the server uses it to identify the state that it holds related to the MQTT session between the client and the server. If a client specifies an empty value as the ClientId, the MQTT server must generate a unique ClientId to identify the client. However, this behavior depends on the value specified for the CleanSession field.
  • CleanSession: The clean session flag is a boolean value that specifies what happens after an MQTT client disconnects from the MQTT server and then reconnects. If CleanSession is set to 1 or true, the client indicates to the MQTT server that the session will only last as long as the network connection is alive. After the MQTT client disconnects from the MQTT server, any information related to the session is discarded. A new connection from the same MQTT client to the MQTT server will not use the data from the previous session and will be a new clean session. If CleanSession is set to 0 or false, we will work with a persistent session. In this case, the MQTT server stores all the subscriptions for the MQTT client and when the MQTT client disconnects, the MQTT server stores all the messages that arrive with specific quality of service levels that match the subscriptions that the MQTT client had at the time the disconnection occurred. This way, when the same MQTT client establishes a new connection with the MQTT server, the MQTT client will have the same subscriptions and will receive all the messages that it couldn't receive when it lost the connection. We will dive deep on the quality of service level for the messages and their relationship with the clean session flag or the persistent session option later.

Tip

When the clean session flag is set to 0 or false, the client indicates to the server that is wants a persistent session. We just have to remember a clean session is the opposite of a persistent session.

  • UserName: If the client wants to specify a user name to request authentication and authorization from the MQTT server, it must set the UserName flag to 1 or true and specify a value for the UserName field.
  • password: If the client wants to specify a password to request authentication and authorization from the MQTT server, it must set the Password flag to 1 or true and specify a value for the Password field.

Tip

We will dedicate the entire next chapter to MQTT security, and therefore, we just mention the fields and the flags that are included in the CONNECT control packtet.

  • ProtocolLevel: The protocol level value indicates the MQTT protocol version that the MQTT client requests the MQTT server to use. Remember we will always work with MQTT version 3.1.1.
  • KeepAliveKeepAlive is a time interval expressed in seconds. If the value for keep alive is not equal to 0, the MQTT client commits to send control packets to the server within the time specified for KeepAlive. If the MQTT client doesn't have to send any control packet, it must send a PINGREQ control packet to the MQTT server, that is, a ping request to tell the MQTT server that the client connection is alive. The MQTT server responds to the PINGREQ control packet with a PINGRESP response to the MQTT client, that is, a ping response to tell the MQTT client that the connection with the MQTT server is alive. The connection is closed when there is an absence of any of these control packets. If the value for keep alive is 0, the keep alive mechanism is turned off.
  • Will, WillQoS, WillRetain, WillTopic and WillMessage: These flags and fields allow the MQTT client to take advantage of the last will and testament feature of MQTT. If the MQTT client sets the Will flag to 1 or true, it specifies that it wants the MQTT server to store a last will message associated with the session. The WillQoS flag specifies the desired quality of service for the last WillMessage and the WillRetain flag indicates whether this messsage must be retained when it is published or not. If the MQTT client sets the Will flag to 1 or true, it must specify the topic for the WillMessage and the message in the WillTopic and WillMessage fields. If the MQTT client is disconnected or loses the connection with the MQTT server, the MQTT server will publish the message specified in the WillMessage field to the topic indicated in the WillTopic field with the chosen quality of service. We will analyze this feature in detail later.

The MQTT server will process a valid CONNECT control packet and it will respond with a CONNACK control packet. This control packet will include values for the following flags included in the header. We want to understand the meaning of these flags because we will be able to retreive their values when we work with MQTT tools and MQTT client libraries.

  • SessionPresent: If the MQTT server received a connection request with the CleanSession flag set to 1 or true, the value for the SessionPresent flag will be 0 or false because no stored session will be reused. If the CleanSession flag was set to 0 or false in the connection request, the MQTT server will work with a persistent session and the value for the SessionPresent flag will be 1 or true if the server had a persistent session for the client from a previous connection and retrieves it. Otherwise, SessionPresent will be 0 or false. The MQTT client that wanted to work with a persistent session can use the value of this flag to determine whether it has to request subscription to the desired topics or whether the subscriptions have been restored from the persisted session.
  • ReturnCode: If the authorization and authentication passed and the connection was successfully established, the value for ReturnCode will be 0. Otherwise, the return code will be different than 0 and the network connection between the client and the server will be closed. The following table shows the possible values for ReturnCode with their meaning.

ReturnCode value

Description

0

The connection was accepted

1

The connection was refused because the MQTT server doesn't support the MQTT protocol version requested by the MQTT client in the CONNECT control packet

2

The connection was refused because the ClientId (client identifier) specified has been rejected

3

The connection was refused because the network connection was established but the MQTT service isn't available

4

The connection was refused because the user name or password values are malformed

5

The connection was refused because authorization failed

Installing a Mosquitto broker on Ubuntu Linux

Now, we will learn the necessary steps to install a Mosquitto broker, also known as Mosquitto MQTT server on the most popular operating systems: Linux, macOS and Windows. First, we will start with Linux; specifically, we will work with Ubuntu Linux. In case you want to work with a different Linux distribution, you can find details about the installation procedure in the Mosquitto downloads section: http://mosquitto.org/download.

Follow these steps to install a Mosquitto broker on Ubuntu Linux. Take into account that you will require root privileges:

  1. Open a Terminal window and run the following command to add the Mosquitto repository:
          sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
    

    After you enter the password, you will see an output similar to the next lines (the temporary file names will be different).

          gpg: keyring `/tmp/tmpj3a50p1p/secring.gpg' created
          gpg: keyring `/tmp/tmpj3a50p1p/pubring.gpg' created
          gpg: requesting key 262C4500 from hkp server keyserver.ubuntu.com
          gpg: /tmp/tmpj3a50p1p/trustdb.gpg: trustdb created
          gpg: key 262C4500: public key "Launchpad mosquitto" imported
          gpg: Total number processed: 1
          gpg:               imported: 1  (RSA: 1)
          OK
    
  2. Run the following command to update the packages with the recently added Mosquitto repository.
          sudo apt-get update
    

    You will see an output similar to the next lines.

          Get:1 http://ppa.launchpad.net/mosquitto-dev/mosquitto-ppa/      ubuntu xenial InRelease [23,8 kB]
          Hit:2 http://security.ubuntu.com/ubuntu xenial-security InRelease
          Hit:3 http://ar.archive.ubuntu.com/ubuntu xenial InRelease
          Hit:4 http://ar.archive.ubuntu.com/ubuntu xenial-updates InRelease
          Get:5 http://ppa.launchpad.net/mosquitto-dev/      mosquitto-ppa/ubuntu xenial/main amd64 Packages [2.048 B]
          Hit:6 http://ar.archive.ubuntu.com/ubuntu xenial-backports InRelease
          Get:7 http://ppa.launchpad.net/mosquitto-dev/      mosquitto-ppa/ubuntu xenial/main i386 Packages [2.048 B]
          Get:8 http://ppa.launchpad.net/mosquitto-dev/mosquitto-ppa/      ubuntu xenial/main Translation-en [1.292 B]
          Fetched 29,2 kB in 1s (21,5 kB/s)
          Reading package lists... Done
    
  3. Now, run the following command to install the package for the Mosquitto server.
          sudo apt-get install mosquitto
    

    You will see an output similar to the next lines. Enter Y and press Enter to answer the question and complete the installation process.

          Reading package lists... Done
          Building dependency tree
          Reading state information... Done
          The following additional packages will be installed:
            libev4 libuv1 libwebsockets7
          The following NEW packages will be installed:
            libev4 libuv1 libwebsockets7 mosquitto
          0 upgraded, 4 newly installed, 0 to remove and 299 not upgraded.
          8 not fully installed or removed.
          Need to get 274 kB of archives.
          After this operation, 714 kB of additional disk space will be used.
          Do you want to continue? [Y/n]
    

    The last lines should include a line that says Setting up mosquitto, as shown in the following lines:

          Setting up mosquitto (1.4.10-0mosquitto3) ...
          Processing triggers for libc-bin (2.23-0ubuntu3) ...
          Processing triggers for systemd (229-4ubuntu7) ...
          Processing triggers for ureadahead (0.100.0-19) ...
    
  4. Run the following command to install the Mosquitto client packages that will allow us to run commands to publish messages to topics and subscribe to topic filters.
          sudo apt-get install mosquitto-clients
    

    You will see an output similar to the next lines. Enter Y and press Enter to answer the question and complete the installation process.

          Reading package lists... Done
          Building dependency tree
          Reading state information... Done
          The following additional packages will be installed:
            libc-ares2 libmosquitto1
          The following NEW packages will be installed:
            libc-ares2 libmosquitto1 mosquitto-clients
          0 upgraded, 3 newly installed, 0 to remove and 299 not upgraded.
          Need to get 138 kB of archives.
          After this operation, 332 kB of additional disk space will be used.
          Do you want to continue? [Y/n]
    

    The last lines should include a line that says Setting up mosquitto-clients, as shown in the following lines:

          Setting up libmosquitto1:amd64 (1.4.10-0mosquitto3) ...
          Setting up mosquitto-clients (1.4.10-0mosquitto3) ...
          Processing triggers for libc-bin (2.23-0ubuntu3) ...
    
  5. Run the following command to check the status for the mosquitto service that was recently installed.
          sudo service mosquitto status
    

    The first lines of the output should be similar to the following lines with an active (running) status displayed. The details after CGroup indicate the command-line that started the service. The -c option followed by /etc/mosquitto/mosquitto.conf specifies that Mosquitto is using this configuration file.

          mosquitto.service - LSB: mosquitto MQTT v3.1 message broker
             Loaded: loaded (/etc/init.d/mosquitto; bad;       vendor preset: enabled)
             Active: active (running)
               Docs: man:systemd-sysv-generator(8)
             CGroup: /system.slice/mosquitto.service
                     └─17560 /usr/sbin/mosquitto -c       /etc/mosquitto/mosquitto.conf
    

    You can also run the following command to check whether the Mosquitto MQTT server is listening at the default port: 1883.

          netstat -an | grep 1883
    

    The following lines show the results of the previous command that indicate the Mosquitto MQTT server has opened an IPv4 and an IPv6 listen socket on port 1883:

          tcp        0      0 0.0.0.0:1883    0.0.0.0:*    LISTEN
          tcp6       0      0 :::1883         :::*         LISTEN
    

Installing a Mosquitto broker on macOS

Follow these steps to install a Mosquitto broker on macOS (known as OS X before version Sierra):

  1. In case you don't have Homebrew installed, open a Terminal window and run the command indicated in the Homebrew homepage, http://brew.sh , to install this popular package manager for macOS. The following command will do the job. However, it is convenient to check the Homebrew homepage and check all the detailed instructions that are always updated with the newest versions of macOS that become available. In case you already have Homebrew installed, move to the next step.
    /usr/bin/ruby -e "$(curl -fsSL
    https://raw.githubusercontent.com/Homebrew
    /install/master/install)"
    
  2. Open a Terminal window and run the following command to request Homebrew to install Mosquitto:
          brew install mosquitto
    
  3. The following lines show the last messages shown in the Terminal that indicate that Homebrew has installed Mosquitto and the instructions to start the MQTT server.
          ==> Installing mosquitto 
          ==> Downloading https://homebrew.bintray.com/bottles/mosquitto-      1.4.10.el_capitan.bottle.tar.gz
          ###################################################### 100.0%
          ==> Pouring mosquitto-1.4.10.el_capitan.bottle.tar.gz
          ==> Caveats
          mosquitto has been installed with a default configuration file.
          You can make changes to the configuration by editing:
              /usr/local/etc/mosquitto/mosquitto.conf
          To have launchd start mosquitto now and restart at login:
            brew services start mosquitto
          Or, if you don't want/need a background service you can just run:
            mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf
          ==> Summary
            /usr/local/Cellar/mosquitto/1.4.10: 32 files, 618.3K
    
  4. After the Mosquitto installation has been completed, run the following command in a new Terminal window to launch Mosquitto with the default configuration file. The -c option followed by /usr/local/etc/mosquitto/mosquitto.conf specifies that we want to use this configuration file.
          /usr/local/sbin/mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf
    

    The following is the output after you run the previous command:

          Gastons-MacBook-Pro:~ gaston$ /usr/local/sbin/mosquitto -c       /usr/local/etc/mosquitto/mosquitto.conf
          1482518967: mosquitto version 1.4.10       (build date 2016-08-31 20:09:41+0100) starting
          1482518967: Config loaded from       /usr/local/etc/mosquitto/mosquitto.conf.
          1482518967: Opening ipv4 listen socket on port 1883.
          1482518967: Opening ipv6 listen socket on port 1883.
    

    The last lines indicate the Mosquitto MQTT server has opened an IPv4 and an IPv6 listen socket on port 1883. Leave the Terminal window opened because we need Mosquitto running on the local computer to work with the next examples.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Make your connected devices less prone to attackers by understanding practical security mechanisms
  • Dive deep into one of IoT’s extremely lightweight machines to enable connectivity protocol with some real-world examples
  • Learn to take advantage of the features included in MQTT for IoT and Machine-to-Machine communications with complete real-life examples

Description

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

Who is this book for?

This book is a great resource for developers who want to learn more about the MQTT protocol to apply it to their individual IoT projects. Prior knowledge of working with IoT devices is essential.

What you will learn

  • Understand how MQTTv3.1 and v3.1.1 works in detail
  • Install and secure a Mosquitto MQTT broker by following best practices
  • Design and develop IoT solutions combined with mobile and web apps that use MQTT messages to communicate
  • Explore the features included in MQTT for IoT and Machine-to-Machine communications
  • Publish and receive MQTT messages with Python, Java, Swift, JavaScript, and Node.js
  • Implement the security best practices while setting up the MQTT Mosquitto broker

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 14, 2017
Length: 280 pages
Edition : 1st
Language : English
ISBN-13 : 9781787285149
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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 14, 2017
Length: 280 pages
Edition : 1st
Language : English
ISBN-13 : 9781787285149
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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 €5 each
Feature tick icon Exclusive print discounts
€264.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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total €67.97 €76.97 €9.00 saved
Hands-On MQTT Programming with Python
€29.99
MQTT Essentials - A Lightweight IoT Protocol
€32.99
Hands-On Internet of Things with MQTT
€32.99
Total €67.97€76.97 €9.00 saved Stars icon

Table of Contents

7 Chapters
1. Lightweight Messaging with MQTT 3.1.1 and Mosquitto Chevron down icon Chevron up icon
2. Securing an MQTT Mosquitto Server Chevron down icon Chevron up icon
3. Controlling a Drone with Python Chevron down icon Chevron up icon
4. Interacting with Sensors in Java Chevron down icon Chevron up icon
5. Controlling Home Automation in JavaScript Chevron down icon Chevron up icon
6. Interacting with Actuators in Swift Chevron down icon Chevron up icon
A. Exersise Answers Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(7 Ratings)
5 star 57.1%
4 star 28.6%
3 star 0%
2 star 0%
1 star 14.3%
Filter icon Filter
Top Reviews

Filter reviews by




Brett Oct 25, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Subscriber review Packt
Grim Sleepless Oct 26, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book on MQTT. I only had issue replicating the TLS part!
Amazon Verified review Amazon
Alexander Pabel Apr 08, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good book which helped me to understand Mqtt protocol and use it in applications of a device which communicates with another device's application via a broker
Amazon Verified review Amazon
Steven C. Ollmann Apr 02, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I purchased to learn about and create working samples for MQTT client. Tested against a sample MQTT server/broker and existing system.I was disappointed that when applying to Google IoT CORE, that Google implements differently. Without this book I would have had a bumpier road to travel. Glad I made this purchase! I learned a lot about MQTT implementations.
Amazon Verified review Amazon
Nitish Nov 04, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Good simple language and explanation is good and easy to understand. Overall a good and useful book. Thanks.
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.