import paho.mqtt.client as mqtt
# Define MQTT broker and topic
broker_address = "test.mosquitto.org"
topic = "your_topic"
# Callback when the client connects to the broker
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT broker")
# Subscribe to a topic if needed
client.subscribe(topic)
else:
print(f"Connection failed with code {rc}")
# Callback when a message is published to the topic
def on_message(client, userdata, message):
print(f"Received message on topic {message.topic}: {message.payload.decode()}")
# Create an MQTT client
client = mqtt.Client()
# Set callback functions
client.on_connect = on_connect
client.on_message = on_message
# Connect to the MQTT broker
client.connect(broker_address, 1883) # Use the appropriate port
# Start the MQTT client loop
client.loop_start()
# Publish a message to the topic (optional)
message = "Hello, MQTT!"
client.publish(topic, message)
# Keep the script running to continue receiving messages
try:
while True:
pass
except KeyboardInterrupt:
print("Disconnected from MQTT broker")
client.disconnect()