29 lines
713 B
Python
29 lines
713 B
Python
import time
|
|||
|
|
import signal
|
||
|
|
import paho.mqtt.client as mqtt
|
||
|
|
|
||
|
|
BROKER = "localhost"
|
||
|
|
PORT = 1883
|
||
|
|
TOPIC = "python/mqtt/test"
|
||
|
|
|
||
|
|
def on_connect(client, userdata, flags, reason_code, properties):
|
||
|
|
print(f"Connected (rc={reason_code})")
|
||
|
|
client.subscribe(TOPIC)
|
||
|
|
|
||
|
|
def on_message(client, userdata, msg):
|
||
|
|
print(f"[{msg.topic}] {msg.payload.decode()}")
|
||
|
|
|
||
|
|
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
||
|
|
client.on_connect = on_connect
|
||
|
|
client.on_message = on_message
|
||
|
|
|
||
|
|
client.connect(BROKER, PORT, 60)
|
||
|
|
client.loop_start()
|
||
|
|
|
||
|
|
# Publish one test message
|
||
|
|
time.sleep(2)
|
||
|
|
client.publish(TOPIC, "Hello from Paho MQTT!", qos=1)
|
||
|
|
print("Published. Listening... (Ctrl+C to exit)")
|
||
|
|
|
||
|
|
# Block forever until SIGINT
|
||
|
|
signal.pause()
|