import easywifi, easydraw, urandom, gc, badge, dialogs, ugfx
from time import *

badge.init()
ugfx.init()
ugfx.input_init()

mqttserver = badge.nvs_get_str("easymqtt", "server", "test.mosquitto.org")
mqttserver = dialogs.prompt_text("MQTT Server", mqttserver)
if mqttserver:
  badge.nvs_set_str("easymqtt", "server", mqttserver) 
  
mqtttopic = badge.nvs_get_str("easymqtt", "topic", "sensors/#")
mqtttopic = dialogs.prompt_text("MQTT Server", mqtttopic)
if mqtttopic:
  badge.nvs_set_str("easymqtt", "topic", mqtttopic) 
  


easydraw.msg("Connecting to WiFi", title = 'Still Connecting Anyway...', reset = True)
easywifi.enable(True)
if easywifi.state==False:
    easydraw.msg("Meh unable to connect to network")
    easydraw.msg("Waiting 5 seconds to try again!")
    badge.eink_busy_wait()
    import machine
    machine.deepsleep(5000)

easydraw.msg("Connecting to MQTT")
from umqtt.simple import MQTTClient

# Received messages from subscriptions will be delivered to this callback
def sub_cb(topic, msg):
    print((topic, msg))
    badge.leds_send_data(''.join(['\0\25\0\0' for i in range(6)]), 24)
    ugfx.clear(ugfx.BLACK)
    ugfx.flush()
    badge.leds_send_data(''.join(['\0' for i in range(24)]), 24)
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()
    badge.leds_send_data(''.join(['\0\25\0\0' for i in range(6)]), 24)
    ugfx.string_box(0,0,296,128,msg,'DejaVuSans20',ugfx.BLACK,ugfx.justifyCenter)
    ugfx.flush()
    badge.leds_send_data(''.join(['\0' for i in range(24)]), 24)

def clear(pressed):
    ugfx.clear(ugfx.BLACK)
    ugfx.flush()
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()

def main(server=mqttserver):
    clientname = 'SHA2017Badge ' + str(urandom.getrandbits(30))
    c = MQTTClient(clientname, server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b""+mqtttopic)
    easydraw.msg("MQTT Connected", title = 'MQTT Notifier', reset = True)
    c.check_msg()
    while True:
        gc.collect()
        c.check_msg()
        sleep(1)
    c.disconnect()


ugfx.input_attach(ugfx.BTN_A, clear)

main()
