Skip to content

Instantly share code, notes, and snippets.

@Tester2009
Created May 27, 2019 06:07
Show Gist options
  • Select an option

  • Save Tester2009/67654b545fdfa739fa95752f727f0a19 to your computer and use it in GitHub Desktop.

Select an option

Save Tester2009/67654b545fdfa739fa95752f727f0a19 to your computer and use it in GitHub Desktop.
Simple Python MQTT communication
# source: https://mntolia.com/mqtt-python-with-paho-mqtt-client/
# source: http://www.steves-internet-guide.com/into-mqtt-python-client/
import paho.mqtt.client as mqtt
broker_host = "iot.eclipse.org"
broker_port = 1883
def on_connect(client, userdata, flags, rc):
print("Connected with result code: "+str(rc))
def on_disconnect(client, userdata, rc):
print("Client got disconnected")
def on_message(client, userdata, message):
print("Message received: "+str(message.payload.decode()))
print("Topic: "+str(message.topic))
print("QOS: "+str(message.qos))
print("Retain flag: "+str(message.retain))
client = mqtt.Client()
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.connect(broker_host, broker_port)
# subscribe
client.subscribe("topic/abc/1", qos=1)
client.loop_forever()
# source: https://mntolia.com/mqtt-python-with-paho-mqtt-client/
# source: http://www.steves-internet-guide.com/into-mqtt-python-client/
import paho.mqtt.client as mqtt
broker_host = "iot.eclipse.org"
broker_port = 1883
client = mqtt.Client()
client.connect(broker_host, broker_port)
# publish
client.publish(topic="topic/abc/1", payload="ABC 123 DEF", qos=1, retain=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment