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:
1 2 3 4 |
python -m pip install paho-mqtt # or python3 -m pip install paho-mqtt |
Verify Installation
To quickly check that the library was correctly installed, we can use Python’s command line interface:
1 2 |
python |
Once inside Python’s interface, attempt to import the library:
1 2 |
import paho.mqtt.client as mqtt |
If the library was found, nothing should be returned.
However, if the library was not found, an error will be thrown:
1 2 3 4 |
Traceback (most recent call last): ... ModuleNotFoundError: No module named 'paho.mqtt.client' |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# Import the Paho MQTT package. import paho.mqtt.client as mqtt # The callback for when the client connects to the broker. def on_connect(client, userdata, flags, rc): print("Connected To Broker") # After establishing a connection, subscribe to the input topic. client.subscribe("consumer/in") # The callback for when a message is received from the broker. def on_message(client, userdata, msg): # Decode the message payload from Bytes to String. payload = msg.payload.decode('UTF-8') # Print the payload to the console. print(payload) # Check if payload is the quit signal. if (payload == "quit"): # If `quit` disconnect the client, ending the program. client.disconnect() if __name__ == "__main__": # Define an Id for the client to use. Id = "consumerPy" # Define the Ip address of the broker. Ip = "localhost" # Create a client. client = mqtt.Client(Id) # Set the callback functions of the client for connecting and incoming messages. client.on_connect = on_connect client.on_message = on_message # Then, connect to the broker. client.connect(Ip, 1883, 60) # Finally, process messages until a `client.disconnect()` is called. client.loop_forever() |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# First, import the Paho MQTT package. import paho.mqtt.client as mqtt # Also, import time for adding a timed delay. import time if __name__ == "__main__": # Next, define an Id for the client to use. Id = "producerPy" # And define the Ip address of the broker. Ip = "localhost" # Then, create a client. client = mqtt.Client(Id) # Connect to the broker. client.connect(Ip, 1883, 60) # Next, begin a loop that will countdown from 10. for i in range(10, 0, -1): # Before sending a message, format the message with the remaining time. message = F"Time Left: {i}" # Now, publish the message to the consumer's in topic. client.publish("consumer/in", message) # Then, sleep for one second to satisfy the countdown timer. time.sleep(1) # Finally, after counting down, send the quit signal to any listeners. client.publish("consumer/in", "quit") |
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.
1 2 |
python SimpleMqttConsumer.py |
In another terminal, execute the SimpleMqttProducer.py
program to begin publishing.
1 2 |
python SimpleMqttPublisher.py |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
Time Left: 10 Time Left: 9 Time Left: 8 Time Left: 7 Time Left: 6 Time Left: 5 Time Left: 4 Time Left: 3 Time Left: 2 Time Left: 1 quit |
The final message, quit
, triggers the SimpleMqttConsumer
to stop looping and return control to the console.