How to Connect to an MQTT Broker Using Paho in Python?

Estimated read time 2 min read

To connect to an MQTT broker using the Paho MQTT client library in Python, you can follow these steps:

  1. Install the Paho MQTT library by running the command pip install paho-mqtt in your terminal or command prompt.
  2. Import the necessary modules in your Python script:
import paho.mqtt.client as mqtt
  1. Define the callback functions for different MQTT events. The three main callback functions are on_connect, on_message, and on_disconnect. Here’s an example:
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
        print("Failed to connect, return code %d" % rc)

def on_message(client, userdata, message):
    print("Received message: " + str(message.payload.decode("utf-8")))

def on_disconnect(client, userdata, rc):
    print("Disconnected from MQTT Broker!")
  1. Create an instance of the MQTT client:
client = mqtt.Client()
  1. Set the callback functions:
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_discon
  1. Connect to the MQTT broker:
broker_address = ""  # Replace with the address of your MQTT broker
port = 1883  # Default MQTT port

client.connect(broker_address, port=port)
  1. Start the MQTT client’s network loop to handle communication with the broker:
  1. Subscribe to MQTT topics if needed:
topic = "your/topic"  # Replace with the topic you want to subscribe to

  1. Publish MQTT messages if needed:
topic = "your/topic"  # Replace with the topic you want to publish to
message = "Hello, MQTT!"

client.publish(topic, message)
  1. Keep the script running to maintain the connection and receive or send MQTT messages. You can add additional logic or sleep statements as needed.
  2. Disconnect from the MQTT broker when done:

Make sure to replace the placeholders with your MQTT broker’s address, port, and the specific topics you want to subscribe to or publish messages on. This basic structure provides a starting point for connecting to an MQTT broker using the Paho MQTT client library in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply