import ugfx, wifi, urandom, system
from time import sleep

wifi.connect()
ugfx.clear(ugfx.WHITE)
ugfx.string(10,10,"Waiting for wifi...","Roboto_Regular12", 0)
ugfx.flush()
wifi.wait()
  
ugfx.clear(ugfx.WHITE)
ugfx.string(10,10,"Connecting to MQTT...","Roboto_Regular12", 0)
ugfx.flush()

from umqtt.simple import MQTTClient

# Received messages from subscriptions will be delivered to this callback
def sub_cb(topic, msg):
    print((topic, msg))

    links, rechts = msg.decode('utf-8').split(';')
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()
    ugfx.string(50,10,links,"Roboto_BlackItalic24",ugfx.BLACK)
    ugfx.string(10,40,rechts,"PermanentMarker36",ugfx.BLACK)
    ugfx.string(40,90,"tickets.sha2017.org","Roboto_BlackItalic24",ugfx.BLACK)
    ugfx.flush()

def main(server="test.mosquitto.org"):
    clientname = 'SHA2017Badge ' + str(urandom.getrandbits(30))
    c = MQTTClient(clientname, server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"tickets.sha2017.org")
    print('mqtt set')
    c.check_msg()
    while True:
        c.check_msg()
        sleep(1)
    c.disconnect()
    
def go_home(pushed):
    if(pushed):
        system.home()
        
ugfx.input_attach(ugfx.BTN_B, go_home)
main()