Lib para MQTT em Python.

Instalação

pip install paho-mqtt

Uso

import paho.mqtt.client as mqtt
 
# Define MQTT broker details
broker = 'my-broker-host'  # Replace with your broker's address
port = 1883  # Typically 1883 for non-SSL, 8883 for SSL
topic = 'mytopic'  # Topic to subscribe/publish
username = 'myuser'  # Replace with your username
password = 'mypasswrd'  # Replace with your password
 
# Define callback for connection
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to broker")
        client.subscribe(topic)  # Subscribe to the topic upon successful connection
    else:
        print(f"Connection failed with code {rc}")
 
# Define callback for received messages
def on_message(client, userdata, msg):
    print(f"Message received: {msg.payload.decode()} on topic {msg.topic}")
 
# Initialize the MQTT client
client = mqtt.Client()
 
# Set username and password
client.username_pw_set(username, password)
 
# Attach callbacks
client.on_connect = on_connect
client.on_message = on_message
 
# Connect to the broker
client.connect(broker, port, 60)
 
# Function to publish a message
def publish_message(client, topic, message):
    client.publish(topic, message)
    print(f"Message '{message}' published on topic '{topic}'")
 
# Start the MQTT client loop to handle reconnects, subscriptions, etc.
client.loop_start()
 
# Example of publishing a message
publish_message(client, topic, "Hello, MQTT!")
 
# Keep the script running for a while to receive messages
try:
    while True:
        pass
except KeyboardInterrupt:
    print("Disconnecting from broker")
    client.loop_stop()
    client.disconnect()