adding mqtt resources
This commit is contained in:
1 parent
54476f6d7b
commit
b683ed2b94
13 files changed
+351
-112
No files matched your search
@@ -0,0 +1,42 @@
|
||||
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.")
|
||||
|
||||
Reference in new issue
Block a user