import umsgpack
import paho.mqtt.client as mqtt
import time
import ssl
import json

cfg = None
with open('config.json') as json_config:
    cfg = json.load(json_config)
connected = False

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    if rc == 0:
        global connected
        connected = True

    client.subscribe('hello/test', qos=1)

def on_message(client, userdata, message):
    p = umsgpack.unpackb(message.payload)
    print("Received message '" + p["message"] + "' on topic '" 
    + message.topic + "' with QoS " + str(message.qos))

def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection.")

mqttc = mqtt.Client()

# mqttc.tls_set_context(context = ssl.create_default_context())

mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.on_message = on_message

mqttc.connect(cfg["mqtt"]["host"], cfg["mqtt"]["port"], cfg["mqtt"]["timeout"])

mqttc.loop_start()

# mqttc.will_set("hello/test", "Disconnected", )

pub = input("Enter something to publish: ")

while pub != 'q':
    if(connected):
        pub = umsgpack.packb({"message":pub})
        mqttc.publish('hello/test', pub)
        pub = input("Enter something to publish: ")
        print('Message is: ' + pub)
    else:
        pub = input('Would you like to reconnect? ')
        if pub == 'y':
            mqttc.reconnect()
        time.sleep(2)

mqttc.loop_stop()
mqttc.disconnect()