Connecting a client to the secured MQTT server with paho-mqtt

First, we will use paho-mqtt to create an MQTT client that connects to the Mosquitto MQTT server. We will write a few lines of Python code to establish a secured connection and subscribe to a topic.

In Chapter 3Securing an MQTT 3.1.1 Mosquitto Server, we secured our Mosquitto server, and therefore, we will use the digital certificates we created to authenticate the client. Most of the time, we will work with an MQTT server that uses TLS, and therefore, it is a good idea to learn how to establish a connection with TLS and TLS authentication. It is easier to establish an unsecured connection with an MQTT server, but it won't be the most common scenario we will face when developing applications that work with MQTT.

First, we need to copy the following files, which we created in Chapter 3Securing an MQTT 3.1.1 Mosquitto Server, to a directory on the computer or device we will use to run a Python script. We saved the files in a directory called mqtt_certificates. Create a board_certificates directory on the computer or board you are going to use as the MQTT client for this example. Copy the following three files to this new directory:

  • ca.crt: Certificate authority certificate file
  • board001.crt: Client certificate file
  • board001.key: Client key

Now, we will create a new Python file named config.py in the main virtual environment folder. The following lines show the code for this file that defines many configuration values that will be used to establish a connection with the Mosquitto MQTT server. This way, all the configuration values are included in a specific Python script. You have to replace the /Users/gaston/board_certificates value in the certificates_path string with the path to the board_certificates directory you created. In addition, replace the value for the mqtt_server_host with the IP address or hostname for the Mosquitto server or any other MQTT server you might decide to use. The code file for the sample is included in the mqtt_python_gaston_hillar_04_01 folder, in the config.py file:

import os.path

# Replace /Users/gaston/python_certificates with the path
# in which you saved the certificate authority file,
# the client certificate file and the client key
certificates_path = "/Users/gaston/python_certificates"
ca_certificate = os.path.join(certificates_path, "ca.crt")
client_certificate = os.path.join(certificates_path, "board001.crt")
client_key = os.path.join(certificates_path, "board001.key")
# Replace 192.168.1.101 with the IP or hostname for the Mosquitto
# or other MQTT server
# Make sure the IP or hostname matches the value
# you used for Common Name
mqtt_server_host = "192.168.1.101"
mqtt_server_port = 8883
mqtt_keepalive = 60

The code declares the certificates_path variable initialized with a string that specifies the path in which you saved the certificate authority file, the client certificate file, and the client key (ca.crt, board001.crt, and board001.key). Then, the code declares the following string variables with the full path to the certificate and key files we need to configure TLS and the TLS client authentication: ca_certificate, client_certificate, and client_key.

The call to os.path.join makes it easy to join the path specified in the certificates_path variable with the filename and generate the full path. The os.path.join function works for any platform, and therefore, we don't have to worry about whether to use a slash (/) or a backslash () to join the path with the filename. Sometimes, we can develop and test in Windows and then run the code on an IoT board that can use different Unix or Linux flavors, such as Raspbian or Ubuntu. The usage of os.path.join makes our job easier in scenarios where we switch between different platforms.

The mqtt_server_host, mqtt_server_port, and mqtt_keepalive variables specify the IP address for the MQTT server (the Mosquitto server), the port that we want to use (8883), and the number of seconds for the keep alive option. It is very important to replace 192.168.1.101 with the IP address for the MQTT server. We specify 8883 for mqtt_server_port because we use TLS and this is the default port for MQTT over TLS, as we learned in Chapter 3Securing an MQTT 3.1.1 Mosquitto Server.

Now, we will create a new Python file named subscribe_with_paho.py in the main virtual environment folder. The following lines show the code for this file that establishes a connection with our Mosquitto MQTT server, subscribes to the vehicles/vehiclepi01/tests topic filter, and prints all the messages received in the subscribed topic filter. The code file for the sample is included in the mqtt_python_gaston_hillar_04_01 folder, in the subscribe_with_paho.py file:

from config import *
import paho.mqtt.client as mqtt


def on_connect(client, userdata, flags, rc):
print("Result from connect: {}".format(
mqtt.connack_string(rc)))
# Subscribe to the vehicles/vehiclepi01/tests topic filter
client.subscribe("vehicles/vehiclepi01/tests", qos=2)

def on_subscribe(client, userdata, mid, granted_qos):
print("I've subscribed with QoS: {}".format(
granted_qos[0]))

def on_message(client, userdata, msg):
print("Message received. Topic: {}. Payload: {}".format(
msg.topic,
str(msg.payload)))


if __name__ == "__main__":
client = mqtt.Client(protocol=mqtt.MQTTv311)
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.on_message = on_message
client.tls_set(ca_certs = ca_certificate,
certfile=client_certificate,
keyfile=client_key)
client.connect(host=mqtt_server_host,
port=mqtt_server_port,
keepalive=mqtt_keepalive)
client.loop_forever()

Note that the code is compatible with paho-mqtt version 1.3.1. Previous versions of paho-mqtt aren't compatible with the code. Hence, make sure you follow the previously explained steps to install paho-mqtt version 1.3.1.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.185.180