import badge, easywifi, ugfx, easydraw, deepsleep, time, virtualtimers, woezel, urandom
from umqtt.simple import MQTTClient

badge.init()
ugfx.init()
badge.vibrator_init()
badge.nvs_set_str('boot', 'splash', 'revdeurbel')

badge.leds_init()
badge.leds_enable()

ugfx.set_lut(ugfx.LUT_FASTER)
ugfx.clear(ugfx.WHITE)

mqttTopic = b"revspace/button/#"
deurbelTopic = b"revspace/button/doorbell"

geel = bytes([128, 255, 0, 0,128, 255, 0, 0,128, 255, 0, 0,128, 255, 0, 0,128, 255, 0, 0,128, 255, 0, 0])

ugfx.flush(ugfx.LUT_FULL)
badge.eink_busy_wait()

def callback(topic, msg):
    message = "%s    %s" % (topic.decode('utf-8'), msg.decode('utf-8'))
    if topic == deurbelTopic:
        print('deurbel')
        badge.leds_enable()
        badge.leds_send_data(geel, 24)
        ugfx.clear(ugfx.BLACK)
        ugfx.flush()
        ugfx.clear(ugfx.WHITE)

        ugfx.string_box(0,45,296,40,"DEURBEL!","PermanentMarker36",ugfx.BLACK, ugfx.justifyCenter)
        ugfx.flush()
        badge.vibrator_activate(0xFF)
		
        badge.leds_disable()
        ugfx.clear(ugfx.BLACK)
        ugfx.flush()
		
        time.sleep_ms(1000)
		
        ugfx.clear(ugfx.WHITE)
        ugfx.string_box(0,45,296,40,"DEURBEL!","PermanentMarker36",ugfx.BLACK, ugfx.justifyCenter)
        ugfx.flush()
        badge.leds_enable()
        badge.leds_send_data(geel, 24)
        badge.vibrator_activate(0xFF)

        badge.leds_disable()
        ugfx.clear(ugfx.WHITE)
        ugfx.flush()		

    print(message)

def process():
    client.check_msg()
    return 100

easywifi.enable(True)
if easywifi.state==False:
    easydraw.msg("Unable to connect to network!","FAILURE")
    easydraw.msg("Waiting 5 seconds to try again!")
    badge.eink_busy_wait()
    deepsleep.start_sleeping(5000)
	
easydraw.msg("Checking for updates")
try:
    woezel.install('revdeurbel')
    easydraw.msg("Updated! Rebooting now!")
    badge.eink_busy_wait()
    import machine
    machine.deepsleep(1)
except:
    # Initialize MQTT
    server = b"mosquitto.space.revspace.nl"
    clientname = 'mqttdeurbelbadge ' + str(urandom.getrandbits(30))
    client = MQTTClient(clientname, server)
    client.set_callback(callback)
    client.connect()
    client.subscribe(mqttTopic)
    virtualtimers.new(100, process, True)
    virtualtimers.activate(100)
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()