1import paho.mqtt.client as mqtt
2
3# The callback for when the client receives a CONNACK response from the server.
4def on_connect(client, userdata, flags, rc):
5 print("Connected with result code " + str(rc))
6 # Subscribing in on_connect() means that if we lose the connection and
7 # reconnect then subscriptions will be renewed.
8 client.subscribe("house/#")
9
10# The callback for when a PUBLISH message is received from the server.
11def on_message(client, userdata, msg):
12 print(str(msg.topic) + " " + str(msg.payload.decode("utf-8")))
13
14client = mqtt.Client()
15client.on_connect = on_connect
16client.on_message = on_message
17
18client.connect("your.host", 1883, 60)
19
20# Blocking call that processes network traffic, dispatches callbacks and
21# handles reconnecting.
22# Other loop*() functions are available that give a threaded interface and a
23# manual interface.
24client.loop_start()
25
26
27# how to publish
28your_data = "data"
29client.publish("your/pub/topic", your_data)
1import paho.mqtt.client as mqtt
2# The callback for when the client receives a CONNACK response from the server.
3def on_connect(client, userdata, flags, rc):
4 print("Connected with result code "+str(rc))
5
6 # Subscribing in on_connect() means that if we lose the connection and
7 # reconnect then subscriptions will be renewed.
8 client.subscribe("$SYS/#")
9
10# The callback for when a PUBLISH message is received from the server.
11def on_message(client, userdata, msg):
12 print(msg.topic+" "+str(msg.payload))
13
14client = mqtt.Client()
15client.on_connect = on_connect
16client.on_message = on_message
17
18client.connect("mqtt.eclipse.org", 1883, 60)
19
20# Blocking call that processes network traffic, dispatches callbacks and
21# handles reconnecting.
22# Other loop*() functions are available that give a threaded interface and a
23# manual interface.
24client.loop_forever()
25# Non blocking : client.loop_start() N.B. need a while True: statement
26