Book Image

Hands-On MQTT Programming with Python

By : Gaston C. Hillar
Book Image

Hands-On MQTT Programming with Python

By: Gaston C. Hillar

Overview of this book

<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>
Table of Contents (9 chapters)

Using the threaded client interface

Now, we will write a new version of the vehicle remote control application to use the threaded interface, also known as the threaded loop. Open the existing vehicle_mqtt_remote_control.py Python file and replace the lines that define the publish_command function with the following lines. The code file for the sample is included in the mqtt_python_gaston_hillar_05_04 folder, in the vehicle_mqtt_remote_control.py file:

def publish_command(client, command_name, key="", value=""): 
    command_message = build_command_message( 
        command_name, key, value) 
    result = client.publish(topic=commands_topic, 
    payload=command_message, qos=2) 
    time.sleep(1) 
    return result 

We removed the following line before the call to time.sleep(1):

    client.loop() 

The threaded loop will automatically call client.loop in another...