How To MQTT In Python

Table of Contents

    Set Up A Local Mosquitto Broker

    Set Up The Paho MQTT Python Packages

    The Python package to be installed is provided by Eclipse Paho, more information can be found here. Follow the instructions provided by the Eclipse Paho foundation to install the MQTT Python package. Or, follow the instructions provided below.

    To install the Paho MQTT python package, use the version of Pip that comes with the Python executable used:

    Verify Installation

    To quickly check that the library was correctly installed, we can use Python’s command line interface:

    Once inside Python’s interface, attempt to import the library:

    If the library was found, nothing should be returned.

    However, if the library was not found, an error will be thrown:

    If an error occurs, try researching your problem to install Paho MQTT with your version of Python.

    Using MQTT in Python: A Data Consumer

    The following program is an example of a simple data consumer built with the Paho MQTT Python Library.

    File SimpleMqttConsumer.py

    Using MQTT in Python: A Data Producer

    The following program is an example of a simple data producer built with the Paho MQTT Python Library.

    File SimpleMqttProducer.py

    Communicating Between The Clients

    With each of the client programs ready to go, we can demonstrate communication between them by running the programs simultaneously.

    In one terminal, execute the SimpleMqttConsumer.py program to begin listening.

    In another terminal, execute the SimpleMqttProducer.py program to begin publishing.

    The SimpleMqttProducer will begin publishing messages to a topic on the MQTT broker. These messages are picked up by the SimpleMqttConsumer and printed to the console.

    The final message, quit, triggers the SimpleMqttConsumer to stop looping and return control to the console.