42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
import time
|
|
import paho.mqtt.client as mqtt
|
|
|
|
# Configuration
|
|
BROKER = "localhost" # Public test broker
|
|
PORT = 1883
|
|
TOPIC = "python/mqtt/test"
|
|
|
|
def on_connect(client, userdata, flags, reason_code, properties):
|
|
print(f"Connected with result code {reason_code}")
|
|
# Subscribe to the topic immediately upon connection
|
|
client.subscribe(TOPIC)
|
|
|
|
def on_message(client, userdata, msg):
|
|
print(f"Received message on {msg.topic}: {msg.payload.decode()}")
|
|
|
|
# Create client instance
|
|
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
|
client.on_connect = on_connect
|
|
client.on_message = on_message
|
|
|
|
# Connect to broker
|
|
try:
|
|
client.connect(BROKER, PORT, 60)
|
|
client.loop_start() # Start network loop in a background thread
|
|
|
|
# Publish a message
|
|
time.sleep(2) # Wait for subscription to settle
|
|
client.publish(TOPIC, "Hello from Paho MQTT!", qos=1)
|
|
print("Message published.")
|
|
|
|
# Keep running to receive messages
|
|
time.sleep(5)
|
|
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
finally:
|
|
# how to disconnect
|
|
# client.loop_stop()
|
|
# client.disconnect()
|
|
print("Disconnected.")
|
|
|