Mosquitto Client Tools and Azure IoT Hub. The beginning of something good....
Published Oct 15 2021 08:00 AM 41.8K Views

Public cloud brings a paradigm shift in what can be done, the art of the possible is possible and in the context of this post, I am planning to connect my existing MQTT-based Smart Home system to Azure.


From ML (Machine Learning) through to anomaly detection and everything in between, the bells and whistles Azure graces myself is far and beyond the capabilities of any on premise system, coupled with low administrative effort of consuming a managed service.


Who has the longest showers? Who wakes up first? Which devices are powered on, yet there is no activity? These questions and many can all be answered from the thousands events occurring each day in my house, but first we need to get these events in to the Cloud, a.k.a. Azure.


The thing is whilst familiar with MQTT, I am new to Azure IoT (and Azure in general). So, in this multi-part series of blog posts, let's learn together as I walk you through my journey.


The inception

Today I use Mosquitto (in Docker container) locally with Home Assistant, Tasmota devices, a PLC and an Arduino Mega. I publish and consume thousands of messages each day (1.4 messages per second, which is mostly PIR data). The easiest path here is to not have these devices publish to Azure IoT Hub (the Azure service used as a Cloud gateway for IoT devices) directly, but to have Mosquitto replicate all messages locally through to Azure IoT Hub.


Remember the three laws of IoT:


  1. The Law of Physics : Latency to the cloud can be unacceptable, think crash avoidance system and medical alerts. So some decision-making must continue to be executed locally on the device. High-value and safety-critical processes must always continue working.

  2. The Law of Economics : The cost of bandwidth is not falling as fast as the cost of storage and compute.

    We might act on low value data locally and upload high value and aggregate data to the cloud for analytics and storage.

  3. The Law of the Land: For legal or compliance reasons, and concerns around privacy, some industries prefer to store data locally more-so, some governments impose data sovereignty restrictions on where data may be stored.

But here, it’s my snarky 10-year-old wondering why there is so much lag when a button is pressed (The law of physics). Therefore, some decision-making must continue to be executed locally and in the absence of Internet connection, my house must continue to function. Ideally something like this image below, once we are publishing events in Azure IoT Hub we are then able to leverage these in the Azure platform as described above.


What I want to doWhat I want to do


The thing is, you need to crawl before you can walk and the first thing I did was to create an Azure IoT Hub instance, create a device identity and publish/subscribe MQTT (version 3.11 compliant) messages via Mosquitto client tools (mosquitto_pub / mosquitto_sub) to Azure IoT Hub, all this using the Azure CLI.


What we will doWhat we will do


The first thing I did was to leverage my favorite search engine to see if this has been done before I found this interesting guide (, and whilst light on details, 2 hours later my MQTT messages started flowing in my IoT Hub, but intially I had many questions. Why use a SAS token for auth? How do I create my Azure IoT Hub? How do I create my device? But more importantly how can I do this in a way that will be part of a build pipeline?


What is Azure IoT Hub?

Azure IoT Hub brings highly secure and reliable communication between your Internet of Things (IoT) application and the devices it manages. Some key features are per-device authentication, built-in device management and scaled provisioning. From an IoT perspective it provides AMQP, MQTT and HTTP endpoints (it's MQTT we will be focusing on in this post). It does a lot, but in the context of this post, think of it as your Cloud gateway for devices that you don't need to manage.


How about AZ-CLI?

Simply put, your CLI (Command Line Interface) for Azure. It is a cross-platform CLI to connect to Azure and execute administrative commands on Azure resources. It allows the execution of commands through a terminal using interactive command-line prompts or a script. The Azure CLI, known as AZ CLI is available across Azure services and is designed to get you working quickly with Azure, with an emphasis on automation and I see it as that interim step between the console and using a direct SDK or service API. You can find more information on Azure CLI here.


You can install the Azure CLI locally on Linux, Mac, or Windows computers. It can also be used from a browser through the Azure Cloud Shell (very cool :thumbs_up::thumbs_up:) or run from inside a Docker container.

I am not going to cover setting up Azure CLI in here. See the Azure CLI setup guide for more information on setting up and configuring for your subscription but suffice to say, Azure CLI ticks that box, which will allow build pipeline integration.Enough about this, lets get started.


The implementation

High Level Steps

  1. Create an Azure IoT Hub instance
  2. Extract Connection Strings
  3. Create an IoT Device identity
  4. Create a SAS Policy
  5. TLS Certificate
  6. Pulling it all together
  7. Mosquitto_pub/Mosquitto_sub


Variables You Will Need To Substitute

This post serves as a high level walkthrough for establishing full duplex (publish and subscribe) communication from your local broker in to Azure. You will be presented with outputs from CLI or from your Azure subscription, that you will need to substitute with your values in order to pass in to the Mosquitto client tools. Some key values you need to substitute are the following:

Device name
SAS token 
Connection string


Step 1: Create the Azure IoT Hub

You will need to firstly create your Azure IoT Hub instance. There are many SKU’s but the F1 SKU provides 8000 messages per day for free and is a good way to get started without incurring cost. Alternate SKU’s can be found here.

az iot hub create --resource-group BaldacchinoRG --name Baldacchino-IOTHub -sku F1 --partition-count 2


The output of this command will provide a lot of JSON. Extract your Azure IoT Hub endpoint. Copy and paste this in to a document in your favourite IDE, we will be adding many values to this document to build out the required.

"hostName": "",


Step 2: Extract the Primary Connection String

You will need to identify the connection string of your IoT Hub

az iot hub connection-string show


This output of this command will provide your connection string (there is two, this will only show the primary). Copy and paste this in to your document.

    "connectionString": ";SharedAccessKeyName=iothubowner;SharedAccessKey=******************************************************=",
    "name": "Baldacchino-IOTHub"

Step 3: Create your device

You now need to create your MQTT device, for the purpose of this walkthrough we will use a SAS token for authentication.

az iot hub device-identity create -n Baldacchino-IOTHub -d Mosquitto


There is no JSON you will need to copy to your clipboard here but you will notice in the JSON output that the type is SAS and we are not using x509 certificates.

"type": "sas",
"x509Thumbprint": {
"primaryThumbprint": null,
"secondaryThumbprint": null
"capabilities": {
"iotEdge": false


Step 4: Generate a SAS token

There are multiple ways to provide Authentication. SAS tokens and x509 certificates are the common approaches. The SAS token is a string that you generate on the client side, and you pass this string to Azure IoT Hub for authentication. Azure IoT Hub then checks the SAS parameters and the signature to verify that it is valid. In a production environment you will likely prefer using X-509 certificates for this authentication but for the sake of my project, SAS token will work.

az iot hub generate-sas-token -d Mosquitto -n Baldacchino-IOTHub


Copy and paste the SharedAccessSignature from the JSON output in your document.

  "sas": "SharedAccessSignature"


Step 5: We need TLS

MQTT typically runs on port 1833 in an unsecure manner but Azure IoT Hub mandates MQTT over TLS on 8883. The root CA might not be part of your Operating System’s keychain and as such you will need to download the PEM file to use with Mosquitto.

You can download the certificate from GitHub at Copy the Baltimore certificate, to save you some time I have pasted this below, and save it as Baltimore.pem




You can validate your TLS certificate by using openSSL

openssl x509 -in Balitore.pem -text
Version: 3 (0x2)
Serial Number: 33554617 (0x20000b9)
Signature Algorithm: sha1WithRSAEncryption
Issuer: C = IE, O = Baltimore, OU = CyberTrust, CN = Baltimore CyberTrust Root
Not Before: May 12 18:46:00 2000 GMT
Not After : May 12 23:59:00 2025 GMT
Subject: C = IE, O = Baltimore, OU = CyberTrust, CN = Baltimore CyberTrust Root
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
X509v3 Basic Constraints: critical
CA:TRUE, pathlen:3
X509v3 Key Usage: critical
Certificate Sign, CRL Sign
Signature Algorithm: sha1WithRSAEncryption


Step 6: Pulling it together

We will soon be using Mosquitto_pub and Mosquitto_sub to publish and subscribe to messages. I am going to assume you have these installed on your local environment.You can easily install this on a Debian based environment with the following command.

sudo apt install mosquitto-clients


For Windows and MAC, see the Mosquitto website. We now have everything we need for Mosquitto but publish and subscribe have different required parameters for publishing and subscribing.

What Mosquitto_pub needs:

mosquitto_pub \
-t "MQTT topic name" \
-i "pub_client" \
-u "username" \
-P "password" \
-h "host name" \
-V mqttv311 \
-p 8883 \
--cafile Baltimore.pem
-m '{"key":"value"}'


What Mosquitto_sub needs:

mosquitto_sub \
-t "MQTT topic name" \
-i "pub_client" \
-u "username" \
-P "password" \
-h "host name" \
-V mqttv311 \
-p 8883 \
--cafile Baltimore.pem


 To publish a MQTT message to Azure, you can not just any topic name. It must be in the following format:


In my example Mosquitto is my DeviceID.

Step 7: Example Publishing and Subscribing

We now have all of the data and understand the required parameters to pass to both Mosquitto_pub and Mosquitto_sub. Now lets leverage these command line tools to build our completed commands and publish a message.

Substitute the values in the examples above with your data. My topic in this example is ‘devices/Mosquitto/messages/events/’. I am using ‘-d’ for verbose logging. 


mosquitto_pub -t "devices/Mosquitto/messages/events/" -i "Mosquitto" -u "" -P "SharedAccessSignature" -h "" -V mqttv311 -p 8883 --cafile Balitore.pem -m '{"key":"value"}' -d

Client Mosquitto sending CONNECT
Client Mosquitto received CONNACK (0)
Client Mosquitto sending PUBLISH (d0, q0, r0, m1, 'devices/Mosquitto/messages/events/', ... (12 bytes))
Client Mosquitto sending DISCONNECT



mosquitto_sub -t "devices/Mosquitto/messages/events/" -i "Mosquitto" -u "" -P "SharedAccessSignature" -h "" -V mqttv311 -p 8883 --cafile Balitore.pem -d

Client Mosquitto sending CONNECT
Client Mosquitto received CONNACK (0)
Client Mosquitto sending SUBSCRIBE (Mid: 1, Topic: devices/Mosquitto/messages/events/, QoS: 0, Options: 0x00)
Client Mosquitto received SUBACK
Subscribed (mid: 1): 0


We can validate the message has been received via Azure IoT Hub by monitoring incoming events on the end-point:

az iot hub monitor-events --hub-name Baldacchino-IOTHubStarting event monitor, use ctrl-c to stop...{"event": {"origin": "Mosquitto","module": "","interface": "","component": "","payload": "'{key:value}'"}}



We just walked through how you can use Mosquitto Client Tools (mosquitto_pub / mosquitto_sub) to publish and subscribe MQTT messages to Azure IoT Hub and you did it not via the Azure Portal but via Azure CLI :flexed_biceps::flexed_biceps:. Whilst this is a baby step, it is the step we need to take before we can look at MQTT broker (the Mosquitto daemon) to Cloud (Azure IoT Hub) replication.

MQTT is the de-facto IoT protocol for devices, from Alexa through to lights and locks and devices on the factory floor. It is as close to an IoT protocol standard that we have today. Azure IoT on the other hand is your gateway in to the world of Cloud. The Azure Cloud platform contains more than 200 (and growing) products and services designed to help you bring your solutions to life, solve today’s challenges and create the future. Join me in part 2 of this multi-part blog series where I will be extending upon what we have just built and will look at broker to Cloud communication before feeding the thousands of events that occur in my house daily in to Azure IoT Hub and beyond.

Think-big and happy automating.

Shane Baldacchino


Version history
Last update:
‎Jul 05 2022 07:37 PM
Updated by: