import ugfx, gc, wifi, badge, deepsleep, urandom
from time import *
psuvoltage='XX.XX'
psucurrent='XX.XX'
psutemperature='XX'
current=['XX.XX','XX.XX', 'XX.XX','XX.XX', 'XX.XX','XX.XX']
notification=['','','','','','']
error=['','','','','','']
ledjes=[0,0,0,0,0,0]

ugfx.init()
ugfx.LUT_FULL
ugfx.input_init()
ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()
ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()
# Make sure WiFi is connected
wifi.init()

ugfx.clear(ugfx.WHITE);
ugfx.string(10,10,"Waiting for wifi...","Roboto_Regular12", 0)
ugfx.flush()

# Wait for WiFi connection
while not wifi.sta_if.isconnected():
    sleep(0.1)
    pass
  
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):
    global psuvoltage
    global psucurrent
    global psutemperature
    global error
    global notification
    global ledjes
    
    print((topic, msg))
    
    #lets strip all the extra characters
    message = (msg.decode('utf-8'))
    message = message.replace('\x08', '')
    message = message.replace('\x05', '')
    
    if(topic.decode('utf-8')=='altpwr/psu/voltage'):
    	psuvoltage = message
    if(topic.decode('utf-8')=='altpwr/psu/current'):
        psucurrent = message
    if(topic.decode('utf-8')=='altpwr/psu/temperature'):
        psutemperature = message

    
    for x in range(0, 6):
        if(topic.decode('utf-8')=='altpwr/psu/'+str(x+1)+'/current'):
           current[x]=message
        if(topic.decode('utf-8')=='altpwr/psu/'+str(x+1)+'/message'):
           notification[x]=message
        if(topic.decode('utf-8')=='altpwr/psu/'+str(x+1)+'/error'):
           error[x]=message
           if(error[x]!=''):
               ledjes[x]=1
           else:
               ledjes[x]=0
    
    ugfx.clear(ugfx.WHITE) 
    ugfx.string(112,1,"ALTPWR.NET PSU","Roboto_Black22", 0)
    #ugfx.string(155,1,"BUILDING A VERSATILE","Roboto_Regular12", 0)
    #ugfx.string(155,11,"DC POWER GRID","Roboto_Regular12", 0)
    badge.eink_png(0,0,'/lib/altpwrnet/altpwr.png')
    ugfx.line(112,23,291,23,ugfx.BLACK)

    ugfx.string(112, 28,psuvoltage + "V, " + psucurrent + "A, " + psutemperature + "*C", "Roboto_Black22", ugfx.BLACK)
    ledstring=''
    for x in range(0,6):
        ugfx.string(112, 50+(x*13),"PSU "+str(x+1)+": "+current[x]+"A", "pixelade13", ugfx.BLACK)
        ugfx.string(175, 50+(x*13), notification[x], "pixelade13", ugfx.BLACK)
        if(ledjes[x]==1):
            ledstring = ledstring +'\x00\x01\x00\x00'
        else:
            ledstring = ledstring + '\x01\x00\x00\x00'
  
    badge.leds_init()
    badge.leds_enable()
    badge.leds_set_state(ledstring)

    ugfx.flush()

def main(server="mqtt.sha2017.org"):
    clientname = 'SHA2017Badge ' + str(urandom.getrandbits(30))
    c = MQTTClient(clientname, server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"altpwr/#")
    print('mqtt set')
    c.check_msg()
    while True:
        c.check_msg()
        sleep(0.1)
    c.disconnect()
    
def go_home(pushed):
    if(pushed):
        import machine
        machine.deepsleep(1)
        
ugfx.input_attach(ugfx.BTN_B, go_home)
main()