Skip to content

Instantly share code, notes, and snippets.

@hyOzd
Created May 14, 2025 12:15
Show Gist options
  • Save hyOzd/2c409a1e9c014e46c3884c7245a7d728 to your computer and use it in GitHub Desktop.
Save hyOzd/2c409a1e9c014e46c3884c7245a7d728 to your computer and use it in GitHub Desktop.
python mqtt request&response example request server
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
"""Example request:
mosquitto_rr -V mqttv5 -h localhost -p 1883 -t "test/topic" -m "Answer this!" -e "test/response"
"""
broker = {'host': "localhost", 'port': 1883}
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected with result code {reason_code}")
client.subscribe("#", options=mqtt.SubscribeOptions(noLocal=True))
def on_message(client, userdata, msg):
print("< ", msg.topic, " ", str(msg.payload))
try:
print("Responding to topic: ", str(msg.properties.ResponseTopic))
client.publish(msg.properties.ResponseTopic, "This is your response")
except:
pass
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, protocol=mqtt.MQTTProtocolVersion.MQTTv5)
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect(broker['host'], broker['port'], 60)
mqttc.loop_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment