'''
example name：MQTT communication (subscribe)
version：v1.0
date：2020.3
Author：01Studio
Forum: forum.01studio.org
'''

import paho.mqtt.client as mqtt
import time

#Server and subject information
host = 'mqtt.p2hp.com'
port = 1883
topic = '/public/01Studio/1'

#The callback function executed when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    #Using subscription topics in on_connect() means that if we lose the connection
    #and reconnect, the subscription will be updated.
    client.subscribe(topic)

# When receiving the release information of other devices from the server,
# execute this callback function.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

#Building an MQTT client
client = mqtt.Client()

#Configure the callback function for connecting and receiving information
client.on_connect = on_connect
client.on_message = on_message

#connect to the server
client.connect(host, port)

#Handle network traffic, dispatch callbacks, and handle blocking calls for reconnection.
client.loop_forever()
